android webview ajax方式添加header,token的方法

????????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:簡書為什么不能插入代碼呢,這可惡的排版。

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容