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

问题描述 投票:0回答:1

我想向https://parts-of-speech.info/tagger/tagger发送POST请求,其参数为“ text =”和“ language =”。

到目前为止,我已经尝试了三个过程:AsyncTask中的JsonObjectRequest,Jsoup.connect和HttpURLConnection,似乎都不起作用。

这是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);

在Logcat中,结果看起来像这样:

BasicNetwork.performRequest: Unexpected response code 404 for https://parts-of-speech.info/tagger/tagger/
W/System.err: com.android.volley.ClientError

这是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();

它在“执行”时崩溃:

E/AndroidRuntime: FATAL EXCEPTION: main

例如,我应该接收JSON对象:

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

我已经在网上搜索了无济于事的解决方案。实现所需结果的最佳方法是什么?

java android post jsoup httpurlconnection
1个回答
0
投票

尝试如下。

 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);
© www.soinside.com 2019 - 2024. All rights reserved.