java - 在 java 中检索响应的 http 代码

标签 java android http

我有以下代码用于发布到 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;
}

最佳答案

您可以这样修改您的代码:

//...
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(..);

关于java - 在 java 中检索响应的 http 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11013468/

相关文章:

java - 设置 Linux 桌面/GUI 环境

android - 如何不断地将GPS数据从android发送到服务器直到应用程序关闭

android - 如何使电子邮件地址可点击?

"could not fulfill request for *known* reason"的 HTTP 状态代码

http - Golang 写入 http 响应会中断输入读取?

java - 将 jsonObject 转换为模型对象时如何检测缺少的字段

java - Eclipse 中的步进过滤器

android - KOTLIN 在键盘显示时调整 fragment ScrollView

cocoa - 如何在 iPhone 上获取 cocoa 中的 http

Java 8 Stream - 为什么过滤器方法不执行?