如何使用webview发布帖子请求?

问题描述 投票:6回答:2

我想使用webview发出http发布请求。

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请求的响应?

提前致谢

android webview http-post response
2个回答
5
投票

WebView不允许您访问HTTP响应的内容。

您必须使用HttpClient,然后使用函数loadDataWithBaseUrl并指定基本URL将内容转发到视图,以便用户可以使用webview继续在网站中导航。

例:

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

10
投票

首先将http库的支持添加到您的gradle文件:能够使用

useLibrary 'org.apache.http.legacy'

在此之后,您可以使用以下代码在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/

© www.soinside.com 2019 - 2024. All rights reserved.