简体   繁体   中英

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

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?

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?

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

}

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

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):

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.

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.

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

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 in Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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