KingFu
KingFu

Reputation: 1358

Android: Disable X-Requested-With Header In WebView

I'm trying to make my WebView headers look like the user is just using the regular browser and not using a WebView. From what I can gather the headers are identical apart that the WebView also sends an X-Requested-With header containing the apps package name. Is there any way of preventing this?

Upvotes: 23

Views: 17048

Answers (2)

Jeeva
Jeeva

Reputation: 4825

Send your own HTTP request like this. to test it navigate to http://httpbin.org/headers from your webview.

override fun shouldInterceptRequest(
    view: WebView?,
    request: WebResourceRequest?
): WebResourceResponse? {
    return try {
        val connection = URL(url).openConnection() as HttpURLConnection
        connection.setRequestProperty("User-Agent", "your_custom_user_agent")
        WebResourceResponse(connection.contentType, connection.contentEncoding, connection.inputStream)
    } catch (_: Exception) {
        null
    }
}

Upvotes: 0

anopid
anopid

Reputation: 139

You can do it for Android API > 11

public class AndroidMobileAppSampleActivity extends Activity {
Map<String, String> extraHeaders = new HashMap<String, String>();
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
    // must define X-Requested-With, if header missing, then webview will
    //add your package name
    extraHeaders.put("X-Requested-With", "your presentation");
    WebSettings webSettings = mainWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    mainWebView.setWebViewClient(new MyCustomWebViewClient());
    mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    mainWebView.loadUrl("http://www.somesite.com", extraHeaders);
}

private class MyCustomWebViewClient extends WebViewClient {
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view,
         String url) {
        // TODO Here you must overwrite request  using your 
        // HttpClient Request
        // and pass it to new WebResourceResponse
        return new  WebResourceResponse(response.ContentType, response.ContentEncoding, responseStream);
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // Apply again your heades here 
        view.loadUrl(url, extraHeaders);
        return true;
    }
}
}

Upvotes: 7

Related Questions