WebView內使用post載入url並新增header
阿新 • • 發佈:2019-01-25
最近專案內需求,使用WebView載入網頁,載入網頁的時候需要post引數去讓網頁生成資料,還要在頭部新增特殊標識
WebView原生的api裡邊有post引數的api
//post是一個byte[]
webview.postUrl(url,post) ;
新增header的Api有
//headers是一個map
webview.loadUrl(url,headers);
這兩個Api只能單獨使用,不能兩個同時使用;
糾結了很長時間,逛玩eoe, csdn各大網站搜尋無果,
最後在stackoverflow 中找到 類似的問題,並且解決,
不廢話了 貼程式碼
打完收工................public class MyWebViewClient extends WebViewClient { @SuppressLint("NewApi") @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { //在這個函式內,可以攔截WebView內的所有url,通過攔截url進行重新封裝HttpUrlConnection 將header新增進連線,post引數寫入 //然後重新生成一個 WebResourceResponse if(!TextUtils.isEmpty(params)){ String mParams = params ; params= null; try { URL mUrl=new URL(url); HttpURLConnection connection= (HttpURLConnection)mUrl.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("resource", "android"); connection.setRequestProperty("client", "clientapp"); DataOutputStream os=new DataOutputStream(connection.getOutputStream()); os.writeBytes(mParams); os.flush(); params =null; return new WebResourceResponse("text/html", connection.getContentEncoding(), connection.getInputStream()); } catch (Exception e) { e.printStackTrace(); }finally{ params =null; } } return super.shouldInterceptRequest(view, url); } }