2016-09-06 163 views
0

我想獲得HttpsURLConnection POST請求的響應。 如果我嘗試使用PostMan來執行請求,我有一條消息作爲回覆(es: 1520)。我必須保存這段代碼,但我發現只讀getResponseCode()(200)或getResponseMessage()(「OK」)的方法。我應該使用其他庫?因爲在HttpsUrlConnection方法我沒有找到什麼有用的東西(https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html獲取POST請求的響應

我的代碼是:

HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); 

    con.setSSLSocketFactory(sslContext.getSocketFactory()); 
    con.setDoOutput(true); 
    con.setUseCaches(false); 
    con.setRequestMethod("POST"); 
    con.setRequestProperty("Connection", "keep-alive"); 
    con.setRequestProperty("Content-Type", w_AECONTYP); 
    con.setRequestProperty("Accept-Charset", w_AEACCCHA); 
    con.setRequestProperty("Accept-Encoding", w_AEACCENC); 

StringBuilder postFile = new StringBuilder(); 
    byte[] postFileBytes =w_FileToSend.getBytes("UTF-8"); 
    con.setDoOutput(true); 
    try { 
    DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 
    wr.write(postFileBytes); 
    wr.flush(); 
    wr.close(); 
    } catch (Exception e) { 
    System.out.println("Connection Failed"); 
    e.printStackTrace(); 
    } 

    int responseCode = con.getResponseCode(); 
    // get 200 code "OK" 

     BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 

    String inputLine; 
    StringBuffer response = new StringBuffer(); 

    while ((inputLine = in.readLine()) != null) { 
    response.append(inputLine); 
    } 

    in.close(); 

但是,當在WHILE循環到達時,它不會在循環進入。 我該怎麼做? 該文件採用JSON格式,但這不是問題。

This is the screen shot of the same POST request with postman (chrome tool

我需要保存915碼!

+0

此代碼產生200響應代碼?我刪除了DataOutputStream的東西,它似乎爲我工作,只要url不重定向。 –

+0

是產生200代碼。還有另一個消息,我需要..但在while((inputLine = in.readLine())!= null)in.readLine爲null! – Simone

+0

你確定你傳遞了正確的URL,並且需要任何頭文件(如果有) URL obj = new URL(url);\t \t HttpsURLConnection con =(HttpsURLConnection)obj.openConnection(); – kuhajeyan

回答

0

你可以使用HttpResponseHttpPost用於獲取來自服務器的響應(以及響應代碼):

HttpResponse httpResponse = httpClient.execute(new HttpPost(URL)); 
InputStream inputStream = httpResponse.getEntity().getContent(); 
InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 
StringBuilder stringBuilder = new StringBuilder(); 
String bufferedStrChunk = null; 
while((bufferedStrChunk = bufferedReader.readLine()) != null){ 
    stringBuilder.append(bufferedStrChunk); 
} 
// now response is in the stringBuilder.toString() 

我希望這會幫助你。