how can i add a custom header to post request on webview

前端 未结 1 1395
梦如初夏
梦如初夏 2020-12-07 04:41

I am now having a problem about post request on webview. Here is the situation: when my webview loaded a login page,and there\'s a form inside which would make the post requ

相关标签:
1条回答
  • 2020-12-07 05:36

    I ran into needing to implement such a feature myself so I'm posting a code snippet for anyone running into the same issue in the future. I'd definitely recommend using OkHttp but the principle (make a request and load the html into the browser in the success callback) should be the same with any other network client.

    protected void postURL(final String url, String postData) {
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Cache-Control", "max-age=0")
                .addHeader("Origin", "null") //Optional
                .addHeader("Upgrade-Insecure-Requests", "1")
                .addHeader("User-Agent", webView.getSettings().getUserAgentString())
                .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Accept-Language", Locale.getDefault().getLanguage())
                .addHeader("Cookie", CookieManager.getInstance().getCookie(url))
                .addHeader("X-Requested-With", BuildConfig.APPLICATION_ID)
                .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), postData))
                .build();
    
        new OkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Timber.e(e.getMessage());
            }
    
            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String htmlString = response.body().string();
    
                webView.post(new Runnable() {
                    @Override
                    public void run() {
                        webView.clearCache(true);
                        webView.loadDataWithBaseURL(url, htmlString, "text/html", "utf-8", null);
                    }
                });
            }
        });
    }
    

    Note that most of those headers are not required but can be used as a guideline to reconstruct an original request issued by the webview itself

    0 讨论(0)
提交回复
热议问题