【问题标题】:Get the Response from POST request从 POST 请求中获取响应
【发布时间】:2016-09-06 16:00:17
【问题描述】:

我想从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 格式,但这不是问题。

我需要保存那个 915 代码!!

【问题讨论】:

  • 此代码产生 200 响应代码?我去掉了 DataOutputStream 的东西,只要 url 没有重定向,它似乎对我有用。
  • 是的,产生 200 个代码。还有另一条消息我需要.. 但是在 while ((inputLine = in.readLine()) != null) in.readLine 是 null!
  • 您确定您传递了正确的 url,以及所需的任何标头(如果有) URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
  • 网址是正确的(我从邮递员那里复制和粘贴)。但我看到它没有发送请求,因为 915 代码是渐进式代码。如果我用邮递员重复 psot,我会得到 916 代码(所以 java 帖子不起作用)。另外,如果我发送错误的文件,我必须得到一个代码。
  • 好吧,当我运行代码时,我还去掉了套接字的东西,所以问题可能就在那里。我想知道如果它仍然返回 200,您是否没有正确验证。

标签: java post inputstream outputstream httpsurlconnection


【解决方案1】:

您可以使用HttpResponse 和HttpPost 从服务器获取响应(以及响应代码):

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()

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多