????????app項目里和m站webview進行交互時,一直存在一個問題,webview在最開始初始化的時候,加了header請求頭和用戶的token,但是如果這個鏈接進行跳轉操作的時候,普通的a標簽進行跳轉頁面的時候,header頭和token還是可以傳過去的,但是如果發(fā)起ajax請求后端接口時,header頭和token頭是帶不過去的,有些需要拿到用戶信息來操作的時候,就會有問題。參照了網(wǎng)上的很多博客,進行處理操作。
webview.setWebViewClient(new setWebViewClient())方法中有一個方法是可以攔截所有的鏈接的,那我們就可以在這個方法里做點兒文章了。
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {}
這個方法雖然已經(jīng)過時了,但是還可以用。
具體代碼如下
```
@Nullable
@Override
public WebResourceResponseshouldInterceptRequest(WebView view, String url) {
String ajaxUrl = url;
? ? ? ? try {
????????????URI uri = URI.create(ajaxUrl);
? ? ? ? ? ? URL url1 = uri.toURL();
? ? ? ? ? ? HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
? ? ? ? ? ? conn.setConnectTimeout(5000);
? ? ? ? ? ? conn.setReadTimeout(5000);
? ? ? ? ? ? conn.setRequestProperty("Authorization", getHeader().get("Authorization"));?// 這里可以設置請求頭
? ? ? ? ? ? conn.setRequestProperty("User-Agent", " xxx/" + DeviceHelper.installVersion());
? ? ? ? ? ? conn.connect();
? ? ? ? ? ? DataInputStream dis =null;
? ? ? ? ? ? // 判斷請求是否成功
? ? ? ? ? ? if (conn.getResponseCode() ==200) {
????????????????// 獲取返回的數(shù)據(jù)
? ? ? ? ? ? ? ? MyLog.error("Get方式請求成功,result--->");
? ? ? ? ? ? }else {
????????????????????MyLog.error("Get方式請求失敗");
? ? ? ? ? ? }
? ? ? ? ? ? ? ? if (conn.getInputStream() !=null) {
????????????????????dis =new DataInputStream(conn.getInputStream());
? ? ? ? ? ? ????}else {
????????????????????return super.shouldInterceptRequest(view, ajaxUrl);
? ? ? ? ? ? ? ? ? ?}
????????????????String mimeType = conn.getContentType();
? ? ? ? ? ? // 關閉連接
? ? ? ? ? ? ????????conn.disconnect();
? ? ? ? ? ? ????????return new WebResourceResponse(mimeType, "UTF-8", dis);
? ? ? ????????? }catch (Exception e) {
????????????????????????e.printStackTrace();
? ? ? ????????? }
????????????return super.shouldInterceptRequest(view, ajaxUrl);
}
```
但是這個方法就是只能用于get請求,因為post方法如果攜帶參數(shù)的話,我們是拿不到的,有點兒問題。
ps:簡書為什么不能插入代碼呢,這可惡的排版。