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