Access the http response headers in a WebView?
Neither WebView
nor WebViewClient
provide methods to do that, Though, you can try to implement that manually. You can do something like this:
private WebView webview;
public void onCreate(Bundle icicle){
// bla bla bla
// here you initialize your webview
webview = new WebView(this);
webview.setWebViewClient(new YourWebClient());
}
// this will be the webclient that will manage the webview
private class YourWebClient extends WebViewClient{
// you want to catch when an URL is going to be loaded
public boolean shouldOverrideUrlLoading (WebView view, String urlConection){
// here you will use the url to access the headers.
// in this case, the Content-Length one
URL url;
URLConnection conexion;
try {
url = new URL(urlConection);
conexion = url.openConnection();
conexion.setConnectTimeout(3000);
conexion.connect();
// get the size of the file which is in the header of the request
int size = conexion.getContentLength();
}
// and here, if you want, you can load the page normally
String htmlContent = "";
HttpGet httpGet = new HttpGet(urlConection);
// this receives the response
HttpResponse response;
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
// la conexion fue establecida, obtener el contenido
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
htmlContent = convertToString(inputStream);
}
}
} catch (Exception e) {}
webview.loadData(htmlContent, "text/html", "utf-8");
return true;
}
public String convertToString(InputStream inputStream){
StringBuffer string = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while ((line = reader.readLine()) != null) {
string.append(linea + "\n");
}
} catch (IOException e) {}
return string.toString();
}
}
I can't test it right now, but that's basically what you could do (it's very crazy though :).
Android WebView - How can I see Headers?
Refer
if you want to get response header,
Access the http response headers in a WebView?
or if you want to attach request header, just use attach map when call webView.loadUrl()
How to load URL with headers in WebView?
Android WebView: Get Response Header HTML
you could get the value by inject a section of js code,here is a simple sample,you could check it.
in the activity :
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_other);
webView = FindViewById<WebView>(Resource.Id.webView1);
webView.SetWebViewClient(new WebViewClientClass());
WebSettings websettings = webView.Settings;
websettings.JavaScriptEnabled = true;
websettings.DomStorageEnabled = true;
webView.AddJavascriptInterface(new Foo(this), "Foo");
webView.LoadUrl("file:///android_asset/demo.html");
}
class WebViewClientClass : WebViewClient
{
public override void OnPageFinished(WebView view, string url)
{
//access to parse < meta name = "viewport" content = "get the value of content" >
view.LoadUrl("javascript:window.Foo.showSource("
+ "document.querySelector('meta[name=\"viewport\"]').getAttribute('content')"
+ ");");
base.OnPageFinished(view, url);
}
}
class Foo : Java.Lang.Object
{
Context context;
public Foo(Context context)
{
this.context = context;
}
[JavascriptInterface]
[Export]
public void showSource(string source)
{
// here you could get the value of meta content
// in this example,i could get source = "width =device-width,initial-scale=1, maximum-scale=1"
Log.Error("content", html);
}
}
the local html :
<html>
<head>
<meta name="viewport" content="width =device-width,initial-scale=1, maximum-scale=1">
</head>
<body>
...
</body>
</html>
How to access all HTTP Response Headers
I've found the answer to my own question.
What I have in my code to return all headers is correct. Using HTTPClient.getResponseHeaders()
is the correct method for iOS and HTTPClient.getAllResponseHeaders()
for Android (no idea why there's two different ways - that could be a question for another day).
The reason I'm not seeing the cookie header is because of a bug in Titanium 1.7.5 (and still exists in 1.8.1). It's not forwarding on the cookie on a 302 redirect.
Jiras on the issues:
- https://jira.appcelerator.org/browse/TIMOB-4537
- https://jira.appcelerator.org/browse/TIMOB-1322
Retrieve HTTP response headers from WKWebview
It looks like you can access the response from the WKNavigationDelegate
method webView:decidePolicyFor:decisionHandler:
.
Set some object as the WKWebView
's navigationDelegate
, and add this method:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
NSDictionary *headers = ((NSHTTPURLResponse *)navigationResponse.response).allHeaderFields;
decisionHandler(WKNavigationResponsePolicyAllow);
}
Related Topics
Android: How to Create a Dialog Without a Title
Android Boot_Completed Not Received When Application Is Closed
Execution Failed for Task 'App:Mergedebugresources' Crunching Cruncher....Png Failed
How to Make Gradient Background in Android
How to Determine If Network Type Is 2G, 3G or 4G
Get JSONarray Without Array Name
How to Group Radiobutton from Different Linearlayouts
How to Call a Local Web Service from an Android Mobile Application
Android Webview with an Embedded Youtube Video, Full Screen Button Freezes Video
Add Ripple Effect to My Button with Button Background Color
Multiline Edittext with Done Softinput Action Label on 2.3
How to Customize Share Intent in Android
How to Display Progress Dialog Before Starting an Activity in Android
Install an APK File from Command Prompt
Android Studio How to Package Single Aar from Multiple Library Projects
Checking Toast Message in Android Espresso
Failed to Find Style 'Coordinatorlayoutstyle' in Current Theme