实现原理:重写WebViewClient中shouldInterceptRequest方法,在Response中添加header达到跨域的作用;
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String urlstr) {
try {
// Our implementation just parses the response and visualizes it. It does not properly handle
// redirects or HTTP errors at the moment. It only serves as a demo for intercepting POST requests
// as a starting point for supporting multiple types of HTTP requests in a full fletched browser
URL url = null;
String fileExtens =null;
if (isProxyUrl) {
fileExtens = MimeTypeMap.getFileExtensionFromUrl(urlstr);
}else{
url=new URL(urlstr);
}
if (TextUtils.isEmpty(fileExtens)){
fileExtens="html";
}
String mimeType = FileStreamType.getStreamType(fileExtens);
if (isProxyUrl) {
url = new URL(generateProxyUrl(urlstr,mimeType));
}
URLConnection rulConnection = url.openConnection();
HttpURLConnection conn = (HttpURLConnection) rulConnection;
conn.setRequestProperty("contentType", mimeType);
conn.setRequestProperty("Accept", mimeType);
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestMethod("GET");
String encodeing =conn.getContentEncoding();
if(TextUtils.isEmpty(encodeing)){
encodeing="utf-8";
}
WebResourceResponse webResourceResponse= new WebResourceResponse(mimeType,encodeing, conn.getInputStream());
Map<String,String> headers=new HashMap<>();
// 解决webView跨域问题
headers.put("Access-Control-Allow-Origin", ApiPath.getInstance().getHostName());
headers.put("Access-Control-Allow-Headers","X-Requested-With");
headers.put("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE");
headers.put("Access-Control-Allow-Credentials", "true");
webResourceResponse.setResponseHeaders(headers);
return webResourceResponse;
// }
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}