簡體   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