Android: How get the status-code of an HttpClient request
Asked Answered
C

3

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?

Calorific answered 7/4, 2010 at 13:37 Comment(0)
Q
211

This will return the int value:

response.getStatusLine().getStatusCode()
Quean answered 7/4, 2010 at 13:42 Comment(5)
Then you can compare with the HTTP status codes developer.android.com/reference/org/apache/http/HttpStatus.htmlSchurman
Since HttpStatus is a deprecated class is there a better class to be used?Chitin
@AkashRamani - Yes, just use the HttpUrlConnection method: .getResponseCode()Jungly
@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.Chitin
@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: developer.android.com/reference/java/net/…Jungly
M
11
if (response.getStatusLine().getStatusCode()== HttpsURLConnection.HTTP_OK){
...
}
Maledict answered 4/3, 2016 at 12:48 Comment(0)
A
0

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

val code = response.code()
Aiden answered 25/3, 2021 at 6:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.