Android Webview POST Android Webview POST android android

Android Webview POST


Two ways to load post response in webview:

  1. webview.loadData(): Like what you have posted in your solution. But "content loaded through this mechanism does not have the ability to load content from the network".

  2. webview.postUrl(): Use this if post response needs to load content from the network. (NOTE: only accessible from api-level 5, which means no android 1.6 or lower)


String postData = "username=my_username&password=my_password";webview.postUrl(url,EncodingUtils.getBytes(postData, "BASE64"));

(source: http://www.anddev.org/other-coding-problems-f5/webview-posturl-postdata-t14239.html)


Try this:

private static final String URL_STRING = "http://www.yoursite.com/postreceiver";public void postData() throws IOException, ClientProtocolException {       List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();       nameValuePairs.add(new BasicNameValuePair("foo", "12345"));       nameValuePairs.add(new BasicNameValuePair("bar", "23456"));     HttpClient httpclient = new DefaultHttpClient();       HttpPost httppost = new HttpPost(URL_STRING);       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));       HttpResponse response = httpclient.execute(httppost);  }

I would recommend doing this as part of an AsyncTask and updating the WebView afterwards


I use webView.loadData() to do client post, and it will display content of url, my code :

public static void webview_ClientPost(WebView webView, String url, Collection< Map.Entry<String, String>> postData){    StringBuilder sb = new StringBuilder();    sb.append("<html><head></head>");    sb.append("<body onload='form1.submit()'>");    sb.append(String.format("<form id='form1' action='%s' method='%s'>", url, "post"));    for (Map.Entry<String, String> item : postData) {        sb.append(String.format("<input name='%s' type='hidden' value='%s' />", item.getKey(), item.getValue()));    }    sb.append("</form></body></html>");    webView.loadData(sb.toString(), "text/html", "UTF-8");      }

use function webview_ClientPost() :

Map<String, String> mapParams = new HashMap<String, String>();      mapParams.put("param1", "111");mapParams.put("param2", "222");Collection<Map.Entry<String, String>> postData = mapParams.entrySet();webview_ClientPost(webView1, "http://www.yoursite.com/postreceiver", postData);