简体   繁体   English

发送带有参数的 POST 请求并读取响应

[英]Sending a POST request with parameters and reading response

I want to send a POST request to https://parts-of-speech.info/tagger/tagger with parameters being "text=" and "language=".我想向https://parts-of-speech.info/tagger/tagger发送一个 POST 请求,参数为“text=”和“language=”。

So far I've tried three procedures: JsonObjectRequest, Jsoup.connect, and HttpURLConnection in AsyncTask, none of which seem to work.到目前为止,我已经尝试了三个过程:AsyncTask 中的 JsonObjectRequest、Jsoup.connect 和 HttpURLConnection,但似乎都不起作用。

This is the code for JsonObjectRequest:这是 JsonObjectRequest 的代码:

Map<String, String> params = new HashMap();
        params.put("text", "This is a text.");
        params.put("language", "en");

        JSONObject parameters = new JSONObject(params);

        JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, stringurl, parameters, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                //TODO: handle success
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                //TODO: handle failure
            }
        });

        Volley.newRequestQueue(this).add(jsonRequest);

This is the track trace:这是轨迹:

2019-10-22 17:46:04.390 19530-19530/? I/hsulaiman.ling: Late-enabling -Xcheck:jni
2019-10-22 17:46:04.992 19530-19530/com.jwanhsulaiman.lingu W/hsulaiman.ling: JIT profile information will not be recorded: profile file does not exits.
2019-10-22 17:46:05.000 19530-19530/com.jwanhsulaiman.lingu I/chatty: uid=10082(com.jwanhsulaiman.lingu) identical 10 lines
2019-10-22 17:46:05.000 19530-19530/com.jwanhsulaiman.lingu W/hsulaiman.ling: JIT profile information will not be recorded: profile file does not exits.
2019-10-22 17:46:05.020 19530-19530/com.jwanhsulaiman.lingu I/Perf: Connecting to perf service.
2019-10-22 17:46:05.038 19530-19530/com.jwanhsulaiman.lingu I/InstantRun: starting instant run server: is main process
2019-10-22 17:46:05.337 19530-19530/com.jwanhsulaiman.lingu W/hsulaiman.ling: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
2019-10-22 17:46:05.339 19530-19530/com.jwanhsulaiman.lingu W/hsulaiman.ling: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
2019-10-22 17:46:05.499 19530-19530/com.jwanhsulaiman.lingu D/OpenGLRenderer: Skia GL Pipeline
2019-10-22 17:46:55.482 19530-19555/com.jwanhsulaiman.lingu I/Adreno: QUALCOMM build                   : 7ae04e7, Ia74c9b5270
    Build Date                       : 09/20/18
    OpenGL ES Shader Compiler Version: EV031.25.03.00
    Local Branch                     : 
    Remote Branch                    : refs/tags/AU_LINUX_ANDROID_LA.UM.7.4.R1.09.00.00.453.030
    Remote Branch                    : NONE
    Reconstruct Branch               : NOTHING
2019-10-22 17:46:55.483 19530-19555/com.jwanhsulaiman.lingu I/Adreno: Build Config                     : S L 6.0.7 AArch64
2019-10-22 17:46:55.483 19530-19555/com.jwanhsulaiman.lingu D/vndksupport: Loading /vendor/lib64/hw/gralloc.msm8998.so from current namespace instead of sphal namespace.
2019-10-22 17:46:55.474 19530-19530/com.jwanhsulaiman.lingu W/RenderThread: type=1400 audit(0.0:375092): avc: denied { search } for name="proc" dev="debugfs" ino=11046 scontext=u:r:untrusted_app:s0:c82,c256,c512,c768 tcontext=u:object_r:qti_debugfs:s0 tclass=dir permissive=0 ppid=2681 pcomm="main" pgid=19530 pgcomm="hsulaiman.lingu"
2019-10-22 17:46:55.487 19530-19555/com.jwanhsulaiman.lingu I/Adreno: PFP: 0x005ff112, ME: 0x005ff066
2019-10-22 17:46:55.491 19530-19555/com.jwanhsulaiman.lingu I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
2019-10-22 17:46:55.492 19530-19555/com.jwanhsulaiman.lingu I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
2019-10-22 17:46:55.492 19530-19555/com.jwanhsulaiman.lingu I/OpenGLRenderer: Initialized EGL, version 1.4
2019-10-22 17:46:55.492 19530-19555/com.jwanhsulaiman.lingu D/OpenGLRenderer: Swap behavior 2
2019-10-22 17:46:55.520 19530-19555/com.jwanhsulaiman.lingu D/vndksupport: Loading /vendor/lib64/hw/android.hardware.graphics.mapper@2.0-impl.so from current namespace instead of sphal namespace.
2019-10-22 17:46:55.521 19530-19555/com.jwanhsulaiman.lingu D/vndksupport: Loading /vendor/lib64/hw/gralloc.msm8998.so from current namespace instead of sphal namespace.
2019-10-22 17:46:56.438 19530-19530/com.jwanhsulaiman.lingu I/AssistStructure: Flattened final assist data: 2648 bytes, containing 1 windows, 10 views
2019-10-22 17:46:56.445 19530-19530/com.jwanhsulaiman.lingu E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2019-10-22 17:46:56.449 19530-19530/com.jwanhsulaiman.lingu I/chatty: uid=10082(com.jwanhsulaiman.lingu) identical 2 lines
2019-10-22 17:46:56.449 19530-19530/com.jwanhsulaiman.lingu E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2019-10-22 17:47:00.065 19530-19628/com.jwanhsulaiman.lingu D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2019-10-22 17:47:00.569 19530-19628/com.jwanhsulaiman.lingu E/Volley: [28257] BasicNetwork.performRequest: Unexpected response code 404 for https://parts-of-speech.info/tagger/tagger/
2019-10-22 17:47:00.581 19530-19530/com.jwanhsulaiman.lingu W/System.err: com.android.volley.ClientError
2019-10-22 17:47:00.581 19530-19530/com.jwanhsulaiman.lingu W/System.err:     at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:199)
2019-10-22 17:47:00.581 19530-19530/com.jwanhsulaiman.lingu W/System.err:     at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:131)
2019-10-22 17:47:00.581 19530-19530/com.jwanhsulaiman.lingu W/System.err:     at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:111)
2019-10-22 17:47:00.581 19530-19530/com.jwanhsulaiman.lingu W/System.err:     at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:90)

This is the code for Jsoup:这是 Jsoup 的代码:

Connection.Response response =
                Jsoup.connect(stringurl)
                        .userAgent("Mozilla/5.0")
                        .timeout(10 * 1000)
                        .method(Method.POST)
                        .data("text", text)
                        .data("language", "en")
                        .followRedirects(true)
                        .execute();
        Document document = response.parse();

It crashes at "execute":它在“执行”时崩溃:

2019-10-22 18:39:56.390 29720-29720/? I/hsulaiman.ling: Late-enabling -Xcheck:jni
2019-10-22 18:39:56.546 29720-29720/? W/hsulaiman.ling: JIT profile information will not be recorded: profile file does not exits.
2019-10-22 18:39:56.547 29720-29720/? I/chatty: uid=10082(com.jwanhsulaiman.lingu) identical 10 lines
2019-10-22 18:39:56.548 29720-29720/? W/hsulaiman.ling: JIT profile information will not be recorded: profile file does not exits.
2019-10-22 18:39:56.561 29720-29720/? I/Perf: Connecting to perf service.
2019-10-22 18:39:56.572 29720-29720/? I/InstantRun: starting instant run server: is main process
2019-10-22 18:39:56.700 29720-29720/? W/hsulaiman.ling: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
2019-10-22 18:39:56.701 29720-29720/? W/hsulaiman.ling: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
2019-10-22 18:39:56.782 29720-29720/? D/OpenGLRenderer: Skia GL Pipeline
2019-10-22 18:39:56.835 29720-29740/? I/Adreno: QUALCOMM build                   : 7ae04e7, Ia74c9b5270
    Build Date                       : 09/20/18
    OpenGL ES Shader Compiler Version: EV031.25.03.00
    Local Branch                     : 
    Remote Branch                    : refs/tags/AU_LINUX_ANDROID_LA.UM.7.4.R1.09.00.00.453.030
    Remote Branch                    : NONE
    Reconstruct Branch               : NOTHING
2019-10-22 18:39:56.836 29720-29740/? I/Adreno: Build Config                     : S L 6.0.7 AArch64
2019-10-22 18:39:56.836 29720-29740/? D/vndksupport: Loading /vendor/lib64/hw/gralloc.msm8998.so from current namespace instead of sphal namespace.
2019-10-22 18:39:56.831 29720-29720/? W/RenderThread: type=1400 audit(0.0:379229): avc: denied { search } for name="proc" dev="debugfs" ino=11046 scontext=u:r:untrusted_app:s0:c82,c256,c512,c768 tcontext=u:object_r:qti_debugfs:s0 tclass=dir permissive=0 ppid=2681 pcomm="main" pgid=29720 pgcomm="hsulaiman.lingu"
2019-10-22 18:39:56.841 29720-29740/? I/Adreno: PFP: 0x005ff112, ME: 0x005ff066
2019-10-22 18:39:56.844 29720-29740/? I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
2019-10-22 18:39:56.844 29720-29740/? I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
2019-10-22 18:39:56.844 29720-29740/? I/OpenGLRenderer: Initialized EGL, version 1.4
2019-10-22 18:39:56.844 29720-29740/? D/OpenGLRenderer: Swap behavior 2
2019-10-22 18:39:56.895 29720-29740/? D/vndksupport: Loading /vendor/lib64/hw/android.hardware.graphics.mapper@2.0-impl.so from current namespace instead of sphal namespace.
2019-10-22 18:39:56.896 29720-29740/? D/vndksupport: Loading /vendor/lib64/hw/gralloc.msm8998.so from current namespace instead of sphal namespace.
2019-10-22 18:39:58.981 29720-29720/com.jwanhsulaiman.lingu I/AssistStructure: Flattened final assist data: 2648 bytes, containing 1 windows, 10 views
2019-10-22 18:39:58.990 29720-29720/com.jwanhsulaiman.lingu E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2019-10-22 18:39:58.992 29720-29720/com.jwanhsulaiman.lingu I/chatty: uid=10082(com.jwanhsulaiman.lingu) identical 2 lines
2019-10-22 18:39:58.992 29720-29720/com.jwanhsulaiman.lingu E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2019-10-22 18:40:02.846 29720-29720/com.jwanhsulaiman.lingu D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2019-10-22 18:40:02.851 29720-29720/com.jwanhsulaiman.lingu D/AndroidRuntime: Shutting down VM
2019-10-22 18:40:02.853 29720-29720/com.jwanhsulaiman.lingu E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.jwanhsulaiman.lingu, PID: 29720
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
        at android.view.View.performClick(View.java:6612)
        at android.view.View.performClickInternal(View.java:6581)
        at android.view.View.access$3100(View.java:785)
        at android.view.View$PerformClick.run(View.java:25904)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:280)
        at android.app.ActivityThread.main(ActivityThread.java:6706)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
        at android.view.View.performClick(View.java:6612) 
        at android.view.View.performClickInternal(View.java:6581) 
        at android.view.View.access$3100(View.java:785) 
        at android.view.View$PerformClick.run(View.java:25904) 
        at android.os.Handler.handleCallback(Handler.java:873) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loop(Looper.java:280) 
        at android.app.ActivityThread.main(ActivityThread.java:6706) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
     Caused by: android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
        at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:117)
        at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105)
        at java.net.InetAddress.getAllByName(InetAddress.java:1154)
        at com.android.okhttp.Dns$1.lookup(Dns.java:39)
        at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)
        at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)
        at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)
        at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
        at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
        at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
        at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
        at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:26)
        at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:730)
        at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:705)
        at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:295)
        at com.jwanhsulaiman.lingu.MainActivity.buttonOnClick(MainActivity.java:68)
        at java.lang.reflect.Method.invoke(Native Method) 
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
        at android.view.View.performClick(View.java:6612) 
        at android.view.View.performClickInternal(View.java:6581) 
        at android.view.View.access$3100(View.java:785) 
        at android.view.View$PerformClick.run(View.java:25904) 
        at android.os.Handler.handleCallback(Handler.java:873) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loop(Looper.java:280) 
        at android.app.ActivityThread.main(ActivityThread.java:6706) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
2019-10-22 18:40:02.869 29720-29720/com.jwanhsulaiman.lingu I/Process: Sending signal. PID: 29720 SIG: 9

I'm supposed to receive a JSON object, for example:我应该收到 JSON object,例如:

{
    "taggedText": "John_NNP likes_VBZ the_DT blue_JJ house_NN at_IN the_DT end_NN of_IN the_DT street_NN ._. "
}

I've searched the web for solutions to no avail.我在 web 中搜索了无济于事的解决方案。 What is the best way to achieve the wanted result?实现预期结果的最佳方法是什么?

Try like below.尝试如下。

 JSONObject parameters = new JSONObject();
 try {
      parameters.put("text" , "sample text");
      parameters.put("language", "en");
 } catch (JSONException e) {
      e.printStackTrace();
 }
 JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, stringurl, parameters,
     new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
           //TODO: handle success
        }
     }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                //TODO: handle failure
            }
      });

Volley.newRequestQueue(this).add(jsonRequest);

UPDATE更新

From your track trace从你的track trace

Unexpected response code 404 for https://parts-of-speech.info/tagger/tagger/ https://parts-of-speech.info/tagger/tagger/的意外响应代码 404

I test your URL using postman it gives response 404 like you.我使用postman它会像您一样给出response 404 but when I try without the last backslash it works fine.但是当我尝试不使用最后一个反斜杠时,它工作正常。

You should remove the last backslash from your URL .您应该从URL中删除最后一个反斜杠 your URL should be like你的 URL 应该像

stringurl = " https://parts-of-speech.info/tagger/tagger " stringurl = " https://parts-of-speech.info/tagger/tagger "

The error I get for Jsoup is UnsupportedMimeTypeException .我为 Jsoup 得到的错误是UnsupportedMimeTypeException It can be solved by adding ignoreContentType(true) to your request:可以通过在您的请求中添加ignoreContentType(true)来解决:

Connection.Response response =
Jsoup.connect("https://parts-of-speech.info/tagger/tagger")
      .userAgent("Mozilla/5.0")
      .timeout(10 * 1000)
      .method(Method.POST)
      .data("text", "This is a text.")
      .data("language", "en")
      .followRedirects(true)
      .ignoreContentType(true)  //Add this line
      .execute();
Document document = response.parse();
System.out.println(document.text());

And the output is: output 是:

{"taggedText":"This_DT is_VBZ a_DT text_NN._. "} {"taggedText":"This_DT is_VBZ a_DT text_NN._."}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM