Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send Post request along with HttpHeaders on Android

I need to post data to server (with "referer" header field) and load the response in 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)

Loads the given URL with the specified additional HTTP headers.

void loadData(String data, String mimeType, String encoding)

Loads the given data into this WebView using a 'data' scheme URL.

void postUrl(String url, byte[] postData)

Loads the URL with postData using "POST" method into this WebView.

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?

like image 967
Atul Goyal Avatar asked Aug 28 '12 07:08

Atul Goyal


1 Answers

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);

Get the response as 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();

Now you can put the html into yourWebView by using loadData():

yourWebView.loadData(html ,"text/html", "UTF-8");
like image 189
ntv1000 Avatar answered Oct 04 '22 01:10

ntv1000