Android Webview sends HTTP header information when Webview opens a web page

  • 2020-06-12 10:35:42
  • OfStack

As is known to all, when you click on a hyperlink to a jump, WebView will automatically current address as Referer (introduction) sent to the server, so a lot of server-side programs by contains referer hotlinking to control, so in some cases, direct input a web address, may have a problem, so how to solve the problem of hotlinking control, actually in webview loads to join a referer is ok, how to add?

Starting with Android 2.2 (also known as API 8), WebView has added a new interface method to make it easier to send other HTTP headers when loading a web page.


public void loadUrl (String url, Map<String, String> additionalHttpHeaders)
Added in API level 8
Loads the given URL with the specified additional HTTP headers.
Parameters
url the URL of the resource to load
additionalHttpHeaders the additional headers to be used in the HTTP request for this URL, specified as a map from name to value. Note that if this map contains any of the headers that are set by default by this WebView, such as those controlling caching, accept types or the User-Agent, their values may be overriden by this WebView's defaults.

Here is a simple demo to show you how to use it.


public void testLoadURLWithHTTPHeaders() {
    final String url = "http://ofstack.com";
    WebView webView = new WebView(getActivity());
    Map<String,String> extraHeaders = new HashMap<String, String>();
    extraHeaders.put("Referer", "http://www.google.com");
    webView.loadUrl(url, extraHeaders);
}

The same applies to other HTTP headers such as UserAgent.


Related articles: