如何使web视图POST请求?(How to make post requests with web

2019-07-03 22:53发布

我想要使​​用的WebView HTTP POST请求。

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

        });

上面的代码片断会在加载网页。 我想访问该请求的响应。

我怎样才能获得使用的WebView HTTP POST请求的响应?

提前致谢

Answer 1:

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

你必须使用的HttpClient对于这一点,然后通过使用该功能将内容转发到视图loadDataWithBaseUrl并指定基础URL,以便用户可以使用web视图继续在网站导航。

例:

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


Answer 2:

首先,HTTP库的支持添加到您的gradle这个文件:为了能够使用

useLibrary 'org.apache.http.legacy'

在此之后,你可以使用下面的代码来执行你的WebView POST请求:

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/



文章来源: How to make post requests with webview?