Android WebView Post Request with Custom Headers

坚强是说给别人听的谎言 提交于 2019-12-05 12:41:11

问题


I could see there are two separate methods in Android docs to post the data and add the headers.

For setting Headers
public void loadUrl (String url, Map<String, String> additionalHttpHeaders)


For setting Post Data
public void postUrl (String url, byte[] postData)

But what I really required is to post the data along with headers. ( Means I want a single method which does both the task ? )

Can somebody please help me out with that.

Thanks :)


回答1:


I've bumped on same problem recently and after couple of hours solved it.

Here is my code snippet with some comments:

HttpClient httpclient = new DefaultHttpClient();

HttpPost httpPost = new HttpPost(getPostUrl());

// example of adding extra header "Referer"
httpPost.addHeader("Referer", getReferer()); 

ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();

for (PostItem postItem : getPostItems()) { 
    // key value post pairs
    // add post parameters in array list
    postParameters.add(new BasicNameValuePair(postItem.getKey(), postItem.getValue())); 
}

HttpResponse response = null;

try {
    mWebView.getSettings().setJavaScriptEnabled(true);
    httpPost.setEntity(new UrlEncodedFormEntity(postParameters));

    response = httpclient.execute(httpPost);

    BasicResponseHandler responseHandler = new BasicResponseHandler();
    String htmlString = responseHandler.handleResponse(response);

    // important!! is to fill base url
    mWebView.loadDataWithBaseURL(getPostUrl(), htmlString, "text/html", "utf-8", null); 

} catch (Exception e){
    // handle errors
}



回答2:


It seems that the framework does not provide these features together.

Looking at the source code of WebViewCore (https://android.googlesource.com/platform/frameworks/base/+/eclair-release%5E2/core/java/android/webkit/WebViewCore.java, line 889), additional headers are processed only in the loadUrl call and never in the postUrl.



来源:https://stackoverflow.com/questions/21754526/android-webview-post-request-with-custom-headers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!