【问题标题】:Retrieve the http code of the response in java在java中检索响应的http代码
【发布时间】:2023-04-05 18:14:01
【问题描述】:

我有以下代码用于向 url 发布帖子并将响应作为字符串检索。但我还想获得 HTTP 响应代码(404,503 等)。我在哪里可以恢复它? 我尝试过使用 HttpReponse 类提供的方法,但没有找到。

谢谢

public static String post(String url, List<BasicNameValuePair> postvalues) {
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);

        if ((postvalues == null)) {
            postvalues = new ArrayList<BasicNameValuePair>();
        }
        httppost.setEntity(new UrlEncodedFormEntity(postvalues, "UTF-8"));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        return requestToString(response);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}


private static String requestToString(HttpResponse response) {
    String result = "";
    try {
        InputStream in = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder str = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            str.append(line + "\n");
        }
        in.close();
        result = str.toString();
    } catch (Exception ex) {
        result = "Error";
    }
    return result;
}

【问题讨论】:

  • response.getStatusLine().getStatusCode() 就在httpclient.execute 之后,所以如果代码是HttpStatus.SC_OK,则在其他情况下调用requestToString 会出错:)
  • @Selvin - 将该评论作为答案怎么样?顺便说一句,+1 是正确的。
  • @Addev 在我的回答中看到我的编辑

标签: java android http


【解决方案1】:

你可以像这样修改你的代码:

//...
HttpResponse response = httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
  //edit: there is already function for this
  return EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
  //Houston we have a problem
  //we should do something with bad http status
  return null;
}

编辑:还有一件事...... 而不是requestToString(..);,你可以使用EntityUtils.toString(..);

【讨论】:

    【解决方案2】:

    你试过了吗?

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        response.getStatusLine().getStatusCode();
    

    【讨论】:

      【解决方案3】:

      您是否尝试过以下方法?

      response.getStatusLine().getStatusCode() 
      

      【讨论】:

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