Android - Get status codes of web pages opened in browser

2k Views Asked by At

In desktop browsers, an extension can trivially obtain the status codes of web pages opened in the browser. By status code I mean 200, 302, 404, 502 etc ...

HTTP response status codes

Response.status

Now say that we have an Android App which is similar to the desktop Chrome extension. This app opens URL links not in a WebView, but in an Android browser.

My question is, is there a way for the app to get the status code of web pages opened in an Android browser? Programmatically through Java, within the Android runtime ... ?

There may just be a way to get these through the Browser content provider or through WebResourceResponse, and I am looking into that.

I do not mean getting the status code of a page downloaded in WebView. There is already a question covering that:

Get HTTP Status Code in Android WebView.

I mean getting the status code of a page opened in an Android browser. How can we get these?

Web-based content

1

There are 1 best solutions below

5
Amirhf On

Sample 1:

URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode(); // show code result :)

This is by no means a robust example; you'll need to handle IOExceptions and whatnot. But it should get you started.

If you need something with more capability, check out HttpClient.

Sample 2:

URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
int statusCode = http.getResponseCode(); // show result :)