2012-06-13 43 views
1

我有以下代碼用於發佈帖子到一個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; 
} 
+4

'response.getStatusLine()getStatusCode()'剛過'httpclient.execute'所以如果代碼是'HttpStatus.SC_OK'你打電話'requestToString'在其他情況下你有錯誤:) – Selvin

+0

@Selvin - 如何使評論成爲答案?這是正確的順便說一句,+1。 – Perception

+1

http://stackoverflow.com/questions/2592843/android-how-get-the-status-code-of-an-httpclient-request – Muse

回答

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

2

你試過以下?

response.getStatusLine().getStatusCode() 
2

您是否嘗試過這個,你可以使用? 。

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