如何使用 java 发送 JSON 字符串数组的 HTTP post 请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34797165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:21:59  来源:igfitidea点击:

How can I use java to send HTTP post request of a JSON array of strings?

javajson

提问by Rahul

I'm trying to implement the http post request to specified in the link: Click here for the link.How can I do so with Java?

我正在尝试实现链接中指定的 http 发布请求:单击此处获取链接。我怎样才能用 Java 做到这一点?

String url = "http://sentiment.vivekn.com/api/text/";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

String urlParameters = "Text to classify";

// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

How do I modify this as to send a JSON array of texts as described in the link and retrieve the results?

我如何修改它以发送链接中描述的 JSON 文本数组并检索结果?

回答by Leo

try this

试试这个

public static void main(String args[]) throws Exception{
    URL url = new URL("http://sentiment.vivekn.com/api/batch/");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(5000);//5 secs
    connection.setReadTimeout(5000);//5 secs

    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-Type", "application/json");

    OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());  
    out.write(
            "[ " +
            "\"the fox jumps over the lazy dog\"," +
            "\"another thing here\" " +
            "]");
    out.flush();
    out.close();

    int res = connection.getResponseCode();

    System.out.println(res);


    InputStream is = connection.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line = null;
    while((line = br.readLine() ) != null) {
        System.out.println(line);
    }
    connection.disconnect();

}

回答by TwinFeats

To read the response, add something like to the bottom of your code:

要阅读响应,请在代码底部添加类似内容:

int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
    reader = new BufferedReader(new    InputStreamReader(connection.getInputStream()));
    StringBuilder sb = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        sb.append(line+"\n");
    }
}

After this, StringBuilder will have the response for you to process.

在此之后,StringBuilder 将有响应供您处理。

To send the JSON request data, you'll need to replace:

要发送 JSON 请求数据,您需要替换:

String urlParameters = "Text to classify";

With

String urlParameters = "{\"no_of_parameters\":1,\"parameters\":{\"1\":true,\"2\":false,\"3\":true},\"service_ID\":\"BT\",\"useCase_ID\":\"SetIgnitionState\"}";

Note the \ in front of the embedded quotes inside the string.

请注意字符串内嵌入引号前面的 \。

Even better is to use a library where you can build your JSON text, like:

更好的是使用一个可以构建 JSON 文本的库,例如:

JSON in Java

Java 中的 JSON

回答by Vika Marquez

Change

改变

String urlParameters = "Text to classify";

to

String urlParameters = "{\"no_of_parameters\":1,\"parameters\":{\"1\":true,\"2\":false,\"3\":true},\"service_ID\":\"BT\",\"useCase_ID\":\"SetIgnitionState\"}"; // It's your JSON-array

回答by Zbynek Vyskovsky - kvr000

First I would rename urlParameters to requestContent. The former is quite confusing as this is content not really parameters. Secondly you either have to either encode it manually or let some existing library to do it for you (Gson for example):

首先,我将 urlParameters 重命名为 requestContent。前者非常令人困惑,因为这是内容而不是真正的参数。其次,您要么必须手动对其进行编码,要么让一些现有的库为您完成(例如 Gson):

Map<String, Object> request = new LinkedHashMap<String, Object>();
request.put("txt", "Text to classify");
Writer writer = new OutputStreamWriter(con.getOutputStream());
Gson.toJson(request, writer);
writer.close();

Similarly back when received response:

收到回复时同样返回:

Map<String, Object> result = Gson.fromJson(new InputStreamReader(con.getInputStream), Map.class);
result.get("result").get("confidence")
... etc

Or you can create data classes for both request and response.

或者您可以为请求和响应创建数据类。