2015-09-25 57 views

回答

0

我跑進需要實現這樣的功能自己,所以我張貼運行任何代碼段將來也會出現同樣的問題。 我肯定會推薦使用OkHttp,但原則(在成功回調中提出請求並將HTML加載到瀏覽器中)應該與任何其他網絡客戶端相同。

protected void postURL(final String url, String postData) { 
    Request request = new Request.Builder() 
      .url(url) 
      .addHeader("Cache-Control", "max-age=0") 
      .addHeader("Origin", "null") //Optional 
      .addHeader("Upgrade-Insecure-Requests", "1") 
      .addHeader("User-Agent", webView.getSettings().getUserAgentString()) 
      .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8") 
      .addHeader("Accept-Language", Locale.getDefault().getLanguage()) 
      .addHeader("Cookie", CookieManager.getInstance().getCookie(url)) 
      .addHeader("X-Requested-With", BuildConfig.APPLICATION_ID) 
      .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), postData)) 
      .build(); 

    new OkHttpClient().newCall(request).enqueue(new Callback() { 
     @Override 
     public void onFailure(Call call, IOException e) { 
      Timber.e(e.getMessage()); 
     } 

     @Override 
     public void onResponse(Call call, final Response response) throws IOException { 
      final String htmlString = response.body().string(); 

      webView.post(new Runnable() { 
       @Override 
       public void run() { 
        webView.clearCache(true); 
        webView.loadDataWithBaseURL(url, htmlString, "text/html", "utf-8", null); 
       } 
      }); 
     } 
    }); 
} 

注意,大多數這些頭都沒有要求,但可以作爲指導重建由web視圖本身

發出原始請求
0

您可以添加loadUrl(Strring url, Map<String, String> extraHeaders) 但這項工作只能在API18 +

另一種方式是

webview.setWebViewClient(new WebViewClient(){ 
     @Override 
     public boolean shouldOverrideUrlLoading(WebView view, String url) { 
      return super.shouldOverrideUrlLoading(view, url); 
     } 

     @Override 
     public WebResourceResponse shouldInterceptRequest(WebView view, String url) { 
      // you can add custom header here 
      return super.shouldInterceptRequest(view, url); 
     } 
    }); 
相關問題