2016-01-14 71 views
0

我试图执行http post请求以在链接中指定:Click here for the link. 我该如何使用Java?如何使用java发送JSON数组字符串的HTTP发布请求?

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数组文本并检索结果?

回答

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

} 
+0

谢谢,它工作完美。 – Rahul

+0

谢谢,这个工程。有些东西我不明白,但是:如果我将'int res'中的代码省略到'disconnect'之前,它不再有效。此外,如果我省去了打印语句,服务器将消除由此产生的死代码。为什么这些陈述是必要的? – Warkst

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 
+0

感谢@that,一个快速noob问题:我在哪里把我批的文本发送它? – Rahul

+0

你称之为“一批文字”?如果你想发送一些数组作为JSON数据,你需要转换你的数组。 样本: 'String [] string = {“one”,“two”}; //这是一个简单的字符串array' 作为JSON字符串它会看起来像: '{ “0”: “一”, “1”: “二”}' 不要忘记使用占位符(” \“)在Java代码中: '{\”0 \“:\”one \“,\”1 \“:\”two \“}' –

+0

明白了,再次感谢。 – Rahul

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 

或者你也可以创建数据用于请求和响应的类。

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文本,如:

JSON in Java