在java中检索响应的http代码

时间:2012-06-13 11:00:53

标签: java android http

我有以下代码来发布一个url的帖子,并以String的形式检索响应。但是我想得到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;
}

3 个答案:

答案 0 :(得分:5)

您可以像这样修改代码:

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

答案 1 :(得分:2)

您是否尝试过以下操作?

response.getStatusLine().getStatusCode() 

答案 2 :(得分:2)

你试过这个吗?

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