如何让与的WebView POST请求?让与、WebView、POST

2023-09-08 00:32:49 作者:清旖

我想用web视图,使一个HTTP POST请求。

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

        });

以上code段加载网页。我想访问该请求的响应。

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

如何获得一个HTTP POST请求的响应?

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

在此先感谢

推荐答案

web视图不会让你访问HTTP响应的内容。

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

您必须使用 HttpClient的的是,然后通过使用该函数 loadDataWithBaseUrl 并指定基本URL,以便用户可以使用web视图继续航行在网站上。

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.

例如:

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