92

I want to download a file and need to check the response status code (ie HTTP /1.1 200 OK). This is a snipped of my code:

HttpGet httpRequest = new HttpGet(myUri);
HttpEntity httpEntity = null;
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpRequest);
...

How do i get the status-code of the response?

whlk
  • 15,487
  • 13
  • 66
  • 96

3 Answers3

211

This will return the int value:

response.getStatusLine().getStatusCode()
Robby Pond
  • 73,164
  • 16
  • 126
  • 119
  • 30
    Then you can compare with the HTTP status codes http://developer.android.com/reference/org/apache/http/HttpStatus.html – thanhbinh84 Dec 27 '11 at 08:30
  • 2
    Since HttpStatus is a deprecated class is there a better class to be used? – gaara87 May 06 '15 at 18:10
  • @AkashRamani - Yes, just use the HttpUrlConnection method: .getResponseCode() – Nikita Kurtin Jul 31 '15 at 21:16
  • 1
    @NikitaKurtin sure that returns an integer but how would you know what the actual response code's Http Response Status is? How would you know if its successful? I dont want to say `if(getResponseCode()==200)`. I'd rather say `if(getResponseCode()==HttpStatus.RESPONSE_OK)` or something like that. – gaara87 Aug 01 '15 at 04:03
  • 3
    @AkashRamani, Yes, it has int Constants inside the class for that. for example HttpURLConnection.HTTP_OK (200 -> http ok status) HttpURLConnection.HTTP_NOT_FOUND (404 -> not found), etc.. full list of available constants you can find in it's class reference: http://developer.android.com/reference/java/net/HttpURLConnection.html#HTTP_ACCEPTED – Nikita Kurtin Aug 02 '15 at 09:20
11
if (response.getStatusLine().getStatusCode()== HttpsURLConnection.HTTP_OK){
...
}
NickUnuchek
  • 11,794
  • 12
  • 98
  • 138
0

Use code() function of response to get its HTTP code:

val code = response.code()
Amin
  • 3,056
  • 4
  • 23
  • 34
HandyPawan
  • 1,018
  • 1
  • 11
  • 16