Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WebView Post Request with Custom Headers [duplicate]

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

like image 936
Vipul Avatar asked Feb 13 '14 12:02

Vipul


1 Answers

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
}
like image 51
Jarda Havelik Avatar answered Oct 22 '22 15:10

Jarda Havelik