在Android上将Post请求与HttpHeaders一起发送 [英] 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);
以 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("\n");
}
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上将Post请求与HttpHeaders一起发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!