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

app项目里和m站webview进行交互时,一直存在一个问题,webview在最开始初始化的时候,加了header请求头和用户的token,但是如果这个链接进行跳转操作的时候,普通的a标签进行跳转页面的时候,header头和token还是可以传过去的,但是如果发起ajax请求后端接口时,header头和token头是带不过去的,有些需要拿到用户信息来操作的时候,就会有问题。参照了网上的很多博客,进行处理操作。

webview.setWebViewClient(new setWebViewClient())方法中有一个方法是可以拦截所有的链接的,那我们就可以在这个方法里做点儿文章了。

public WebResourceResponse shouldInterceptRequest(WebView view, String url) {}

这个方法虽然已经过时了,但是还可以用。

具体代码如下

```

@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) {

// 获取返回的数据

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方法如果携带参数的话,我们是拿不到的,有点儿问题。

ps:简书为什么不能插入代码呢,这可恶的排版。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值