2016-09-06 202 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() 

我希望这会帮助你。