2016-01-14 68 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