从POST请求获取响应

时间:2016-09-06 16:00:18

标签: java post inputstream outputstream httpsurlconnection

我想从HttpsURLConnection POST请求中获取响应。 如果我尝试使用PostMan执行请求,则会有一条消息作为回复(es: 1520)。我必须保存此代码,但我发现只读取getResponseCode()(200)或getResponseMessage()(" OK")的方法。我应该使用另一个库?因为在HttpsUrlConnection方法中我找不到任何有用的内容(https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html

我的代码是:

  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代码!!

1 个答案:

答案 0 :(得分: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()

我希望这会对你有所帮助。