【问题标题】:How to make post requests with webview?如何使用 webview 发出帖子请求?
【发布时间】:2012-11-19 10:53:21
【问题描述】:

我想使用 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;
            }

        });

上面的代码 sn -p 加载网页。我想访问此请求的响应。

如何使用 webview 获取 http post 请求的响应?

提前致谢

【问题讨论】:

  • 在这种情况下,webView 没有任何作用,webView 只是让您的网页显示在 android 小工具中,现在由您在服务器站点上处理您网站中的请求响应,我建议您使用 HTTPPOST 调用来获取响应
  • 您的问题是:如何使用网页视图发出帖子请求?比您问的详细信息:如何使用 Web 视图获取 http post 请求的响应?那么你真正的问题是什么?因此我投了反对票。

标签: android webview http-post response


【解决方案1】:

首先将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/

【讨论】:

  • EncodingUtils 已弃用,无法使用
  • @war_Hero EncodingUtils 的替代品是什么
  • URLEncoder.encode 返回一个字符串,而不是一个字节[]。调用 .getBytes() 会起作用吗?
【解决方案2】:

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

【讨论】:

  • 如何将 http post 请求与 loadDataWithBaseUrl 一起使用?
  • 我在答案中添加了一个示例
猜你喜欢
  • 2018-06-07
  • 1970-01-01
  • 1970-01-01
  • 2017-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-02
  • 2019-11-20
相关资源
最近更新 更多