在 Android 上与 HttpHeaders 一起发送 Post 请求 [英] Send Post request along with HttpHeaders on Android
问题描述
我需要将数据发布到服务器(带有referer"标头字段)并在 Webview 中加载响应.
I need to post data to server (with "referer" header field) and load the response in Webview.
现在,有不同的方法(来自 Android WebView)来完成其中的一部分,就像有:
Now, there are different methods (from Android WebView) to do parts of it, like there is:
void loadUrl(String url, Map<String, String> additionalHttpHeaders)
使用指定的附加 HTTP 标头加载给定的 URL.
Loads the given URL with the specified additional HTTP headers.
void loadData(String data, String mimeType, String encoding)
使用数据"方案 URL 将给定数据加载到此 WebView 中.
Loads the given data into this WebView using a 'data' scheme URL.
void postUrl(String url, byte[] postData)
使用POST"方法将带有 postData 的 URL 加载到此 WebView 中.
Loads the URL with postData using "POST" method into this WebView.
loadUrl() 允许发送 HttpHeaders 但不允许发送 post 数据,其他方法似乎不允许发送 HttpHeaders.我是否遗漏了什么或我正在尝试的东西是不可能的?
loadUrl() allows to send HttpHeaders but doesn't allow to send post data, other methods seem to be not allowing to send HttpHeaders. Am I missing something or what I am trying is not possible?
推荐答案
你可以像这样手动执行HttpPost
:
You can execute the HttpPost
manually like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/postreceiver");
// generating your data (AKA parameters)
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("ParameterName", "ParameterValue"));
// ...
// adding your headers
httppost.setHeader("HeaderName", "HeaderValue");
// ...
// adding your data
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
获取 response
作为 String
:
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("
");
}
String html = builder.toString();
现在您可以使用 loadData()
将 html
放入 yourWebView
中:
Now you can put the html
into yourWebView
by using loadData()
:
yourWebView.loadData(html ,"text/html", "UTF-8");
这篇关于在 Android 上与 HttpHeaders 一起发送 Post 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!