【问题标题】:Android WebView Post Request with Custom Headers [duplicate]带有自定义标头的Android WebView发布请求[重复]
【发布时间】:2014-03-12 08:21:30
【问题描述】:

我可以看到 Android 文档中有两种不同的方法来发布数据和添加标题。

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


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

但我真正需要的是与标题一起发布数据。 (意味着我想要一个同时完成这两个任务的方法?)

谁能帮帮我。

谢谢:)

【问题讨论】:

  • 嗨。我知道这已经过时了,但我需要实现与您相同的目标。你能找到一个干净的解决方案吗?谢谢。

标签: android post webview http-headers


【解决方案1】:

我最近遇到了同样的问题,几个小时后解决了。

这是我的代码 sn-p 和一些 cmets:

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
}

【讨论】:

  • 我认为 HttpClient 在 Android 上已被删除。您能否分享此代码的替代方法?
【解决方案2】:

似乎框架没有同时提供这些功能。

查看 WebViewCore 的源代码(https://android.googlesource.com/platform/frameworks/base/+/eclair-release%5E2/core/java/android/webkit/WebViewCore.java,第 889 行),额外的标头仅在 loadUrl 调用中处理,而从不在 postUrl 中处理。

【讨论】:

    猜你喜欢
    • 2015-12-22
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 2016-12-31
    • 2016-11-12
    • 2012-05-17
    相关资源
    最近更新 更多