5

How do I access response headers and status code (along with cookies which I know how to get) in web in Android app?

In our app, I need to access these data for a custom authentication via web login, similar to OAuth but also need headers etc. This is something I took for granted as I have had no problem in other platforms before, but not Android. For completion, I am doing all these via Xamarin wrappers libraries.

The closest way I got is from this question: Access the http response headers in a WebView? ... but it is 4 years old and the manual intercepting might not work for us as we are only using the URL. I also consider prompting a browser but it seems to give even less control.

Is there a way to achieve this in Android?

Community
  • 1
  • 1
M W
  • 1,269
  • 5
  • 21
  • 31
  • Can you elaborate why "the manual intercepting might not work for us as we are only using the URL" ? The answer if four year old but seems to work, if you targeting api 22 (which I doubt) you can override 'shouldInterceptRequest(WebView, WebResourceRequest)'. You have the header in the WebResourceRequest – Guilherme Torres Castro May 20 '15 at 16:23
  • The manual interception suggested in the link would send a request using only the URL, missing any cookies, headers and possibly body. – M W May 20 '15 at 16:30
  • Not it does not. It´s suggested that you responsible to provide the HttpRequest and HttpResponse given a url. You have total control of those, you can set head, cookies, body and etc in the request before execute it and get all necessary resources from the HttpResponse. – Guilherme Torres Castro May 20 '15 at 16:43
  • The problem is that these info has to come from somewhere. I don't have them (hence the question). – M W May 20 '15 at 16:52
  • 2
    I'm sorry, but the answer is still the same as 4 years before. WebView doesn't provide access to response headers and HTTP status code. You have to use a HTTP client and retrieve the page yourself if you need to access this data. – Mikhail Naganov May 20 '15 at 17:49
  • Thanks. I think I can do that. I just need to save a cache of whatever I need from the response for next call. I think that's what you mean Guilherme Torres Castro. – M W May 20 '15 at 20:48

1 Answers1

0

WebView doesn't provide access to response headers and HTTP status code. You have to use a HTTP client

 private readonly HttpClient client;
 client = new HttpClient();

 private const string Url = "Your Base Url";
 client.BaseAddress = new Uri(Url);

 var response = await client.GetAsync(string.Format("Your Request Url"));
        response.EnsureSuccessStatusCode();

        var header = response.Headers;
        var statusCode = response.StatusCode;
        var requestMessage = response.RequestMessage;

So from the response object you can get the response Header, StatusCode and all others

Amalan Dhananjayan
  • 2,277
  • 1
  • 34
  • 47