如何在Android上将POST请求加载到具有标题和正文的Webview

时间:2019-06-09 17:15:54

标签: java android webview

所以我有一个url,一堆标题和一个包含几个json格式值的主体,需要将它们加载到Webview中。以下代码似乎无效。

public void createWebview(){

    WebView webView = (WebView) findViewById(R.id.webview);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webView.setWebViewClient(new MyWebViewClient());      
    String data = '{
                     "data1" : "data1",
                     "data2" : "data2",
                     "data3" : "data3"

                   }';

    try {
        webView.postUrl("https://www.example.com",data.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

private class MyWebViewClient extends WebViewClient

{

    @Override
    public WebResourceResponse shouldInterceptRequest (WebView view, WebResourceRequest request)
    {
        request.getRequestHeaders().put("header1", "header1");
        request.getRequestHeaders().put("header2", "header2");
        request.getRequestHeaders().put("header3", "header3");                 
        return super.shouldInterceptRequest(view,request);
    }
}

我们非常感谢您的帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

我认为也许您应该弄清流程的每个部分,

1)在onCreateView上: -声明webview: ...

    WebView webView = (WebView) findViewById(R.id.webview);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webView.setWebViewClient(new MyWebViewClient());
    // Maybe you want to show Please wait Dialog to let user wait

    inflateUI();

... 2)然后,您使用翻新请求发布以获取数据。 ...

void inflateUI() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {.. use Retrofit to get Data by Post }
          }
      }

... 3)然后在Webview中更新数据。

翻新版:https://medium.com/@prakash_pun/retrofit-a-simple-android-tutorial-48437e4e5a23