45

I am trying to accomplish something quite simple, yet I have found no good documentation on this. I have a webView, and I need to load a page in it that requires POST data. Seems like a simple process, yet I cannot find a way to display the result in a webView.

The process should be simple:

query(with POST data) -> webserver -> HTML response -> WebView.

I can submit data using a DefaultHttpClient, but this cannot be displayed in a WebView.

Any suggestions?

Much Thanks

Solution

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);  
         String data = new BasicResponseHandler().handleResponse(response);
         mWebView.loadData(data, "text/html", "utf-8");
    }
Señor Reginold Francis
  • 16,318
  • 16
  • 57
  • 73

5 Answers5

145

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)

Kaushik
  • 6,150
  • 5
  • 39
  • 54
tarkeshwar
  • 4,105
  • 4
  • 29
  • 35
  • I think this is the better way to do it. But how about uploading an image file? Could it be done with this method? – leninyee Aug 29 '11 at 05:29
  • 8
    @tarkeshwar Unbelievable. SO is full of long and [cumbersome](http://stackoverflow.com/questions/1652850/android-webview-cookie-problem/2349340#2349340) half-baked solutions that require [separate](http://stackoverflow.com/questions/5716898/set-a-cookie-to-a-webview-in-android/5717294#5717294) cookie handling & management, and here you come, posting a solution that does it all with 2 lines only. I would have voted you up +100 but SO only allows +1. IMHO this should be the accepted answer. Thank you for saving me a lot of time! – ateiob Aug 30 '11 at 00:44
  • 1
    Best answer for this question in my view – Jscti May 09 '12 at 14:35
  • 8
    Does the `String postData` **have** to be base64 encoded, or can't we just use `String.getBytes()` to get the `byte[]`? – Tony Chan Jul 26 '12 at 20:18
  • getBytes's second paramater is the desired encoding, so correct me if I am wrong but it should be something like "UTF8", right? If invalid, it will use the system default, hence it still works [link to documentation](http://developer.android.com/reference/org/apache/http/util/EncodingUtils.html) – Pedro Loureiro Oct 22 '13 at 11:01
  • @tarkeshwar what about this? `HttpPost hp = new HttpPost();` `HttpParams par = hp.getParams();` and `par.setStringParam("name","value");` `mwebview.postUrl(url, par.toString().getBytes());` – johntheripp3r Oct 30 '13 at 14:54
  • Best answer , Thank you @tarkeshwar – Parth Anjaria Mar 23 '16 at 10:10
  • Is there an alternative to EncodingUtils as those a deprecated nowadays? – althaus Apr 01 '16 at 09:47
  • 4
    I think `EncodingUtils` comes from Apache Commons, however Android contains `android.utils.Base64` which can perform the same task: `Base64.encode(params.getBytes(), Base64.DEFAULT);` – Andrea Lazzarotto May 05 '16 at 13:53
  • if you not see EncodingUtils, add "android { useLibrary 'org.apache.http.legacy' }" to your gradle – javad Dec 24 '16 at 07:41
  • Just had to use `URLEncoder.encode` while adding the user name and the password as the post parameters. – Reaz Murshed Nov 11 '17 at 14:51
  • Woking for me without base64 encoding. – Sean Apr 02 '18 at 07:54
  • and how about setting token in header? – Hojat Modaresi Sep 02 '18 at 12:00
16

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

TJF
  • 569
  • 4
  • 12
  • I have a piece of code quite similar to this, but I have no idea how to relate this with a WebView. If it isnt too much trouble, could you post a snippet of a WebView using this piece of code? Thanks – Señor Reginold Francis Aug 13 '10 at 13:17
  • Once you have the data, do you merely want to display the results in the `WebView`, or are you wanting the user to continue clicking links? I believe once you load data from a `String` you can't interact with it. Elaborate a little more. ;-) – TJF Aug 13 '10 at 13:29
  • All I really want to do is submit POST data do a page, and then display the resulting page to the user – Señor Reginold Francis Aug 13 '10 at 14:10
  • I guess I should add that the user will click links once viewing the webview if that is what you are asking, but the webview is configured to handle that already – Señor Reginold Francis Aug 13 '10 at 14:28
  • Solved it. Refer to top for my solultion. Marking your answer as correct as it does the bulk of the work – Señor Reginold Francis Aug 13 '10 at 15:23
  • Just be wary of this caveat from the docs: `Content loaded through this mechanism does not have the ability to load content from the network.` -- I'm not sure if that means you won't be able to interact with it once it is loaded or if it won't load `` tags, or what. Thx for the accept! – TJF Aug 13 '10 at 19:42
12

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);
HenryChuang
  • 1,449
  • 17
  • 28
2

If you use a WebView from the start could it work?

A Webview with a html/js that does the POST, and naturally displays the result.

LatinSuD
  • 1,779
  • 12
  • 19
2

You can also pass post key:value pair in JSON format to web view.

String userName = "admin";
String password = "Admin@2021"; 
    JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userName", userName);
            jsonObject.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
        }

String url = "http://www.example.com";
webView.postUrl(url, jsonObject.toString().getBytes());
Mayur Misal
  • 806
  • 10
  • 13