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

这个方法虽然已经过时了,但是还可以用。
但是这个方法就是只能用于get请求,因为post方法如果携带参数的话,我们是拿不到的,有点儿问题。
具体代码如下


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

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。