我有以下代碼用於發佈帖子到一個url作爲字符串檢索響應。但我想獲得HTTP響應代碼(404,503等)。我可以在哪裏找到它? 我試過用HttpReponse類提供的方法,但沒有找到它。在java中檢索響應的http代碼
感謝
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
@Selvin - 如何使評論成爲答案?這是正確的順便說一句,+1。 – Perception
http://stackoverflow.com/questions/2592843/android-how-get-the-status-code-of-an-httpclient-request – Muse