繁体   English   中英

从POST请求获取响应

[英]Get the Response from POST request

我想从HttpsURLConnection POST请求获取响应。 如果我尝试通过PostMan发出请求, 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格式,但这不是问题。

这是与邮递员(chrome工具)相同的POST请求的屏幕截图

我需要保存915代码!

您可以使用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()

我希望这能帮到您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM