我正在尝试实现链接中指定的http post请求:Click here for the link. 我怎么能用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();
如何将其修改为发送链接中描述的JSON文本数组并检索结果?
答案 0 :(得分:5)
试试这个
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();
}
答案 1 :(得分:0)
更改
String urlParameters = "Text to classify";
到
String urlParameters = "{\"no_of_parameters\":1,\"parameters\":{\"1\":true,\"2\":false,\"3\":true},\"service_ID\":\"BT\",\"useCase_ID\":\"SetIgnitionState\"}"; // It's your JSON-array
答案 2 :(得分:0)
首先,我将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();
同样回到收到回复时:
Map<String, Object> result = Gson.fromJson(new InputStreamReader(con.getInputStream), Map.class);
result.get("result").get("confidence")
... etc
或者您可以为请求和响应创建数据类。
答案 3 :(得分:0)
要阅读回复,请添加类似于代码底部的内容:
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");
}
}
在此之后,StringBuilder将为您提供处理响应。
要发送JSON请求数据,您需要替换:
String urlParameters = "Text to classify";
使用
String urlParameters = "{\"no_of_parameters\":1,\"parameters\":{\"1\":true,\"2\":false,\"3\":true},\"service_ID\":\"BT\",\"useCase_ID\":\"SetIgnitionState\"}";
注意字符串中嵌入引号前面的\。
更好的方法是使用可以构建JSON文本的库,例如: