10

I want to make an http post request using webview.

webView.setWebViewClient(new WebViewClient(){


            public void onPageStarted(WebView view, String url,
                Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            }

            public boolean shouldOverrideUrlLoading(WebView view,
                String url) {

            webView.postUrl(Base_Url, postData.getBytes());

            return true;
            }

        });

The above code snippet loads the webpage. I want to access the response of this request.

How can i obtain the response of an http post request using webview?

Thanks in Advance

Devu Soman
  • 2,246
  • 13
  • 36
  • 57
  • there is no role of webView in this scenario , webView simply lets your webpage display in the android gadgets , now its uoto you to handle the request response in your website on the server site , i would suggest you use HTTPPOST calls to take the response – Hussain Akhtar Wahid 'Ghouri' Nov 19 '12 at 11:23
  • 1
    Your question is: How to make post requests with web view? Than in details you ask: How can i obtain the response of an http post request using web view? So what is your real question? Hence my down vote. – AndaluZ Mar 04 '16 at 09:58

2 Answers2

12

First add the support of the http library to your gradle file: To be able to use

useLibrary 'org.apache.http.legacy'

After this you can use the following code to perform post request in your webview:

public void postUrl (String url, byte[] postData)
String postData = "submit=1&id=236";
webview.postUrl("http://www.belencruzz.com/exampleURL",EncodingUtils.getBytes(postData, "BASE64"));

http://belencruz.com/2012/12/do-post-request-on-a-webview-in-android/

Ever CR
  • 351
  • 3
  • 7
TibiG
  • 819
  • 1
  • 6
  • 18
9

The WebView does not let you access the content of the HTTP response.

You have to use HttpClient for that, and then forward the content to the view by using the function loadDataWithBaseUrl and specifying the base url so that the user can use the webview to continue navigating in the website.

Example:

// Executing POST request
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(postContent);
HttpResponse response = httpclient.execute(httppost);

// Get the response content
String line = "";
StringBuilder contentBuilder = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = rd.readLine()) != null) { 
    contentBuilder.append(line); 
}
String content = contentBuilder.toString();

// Do whatever you want with the content

// Show the web page
webView.loadDataWithBaseURL(url, content, "text/html", "UTF-8", null);
James Goodwin
  • 7,360
  • 5
  • 29
  • 41
Nicolas Dusart
  • 1,867
  • 18
  • 26