自Android API 21级起,现在可以实现此功能。您可以像这样创建OPTIONS响应:
public class OptionsAllowResponse {
static final SimpleDateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy kk:mm:ss", Locale.US);
@TargetApi(21)
static WebResourceResponse build() {
Date date = new Date();
final String dateString = formatter.format(date);
Map<String, String> headers = new HashMap<String, String>() {{
put("Connection", "close");
put("Content-Type", "text/plain");
put("Date", dateString + " GMT");
put("Access-Control-Allow-Origin", );
put("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
put("Access-Control-Max-Age", "600");
put("Access-Control-Allow-Credentials", "true");
put("Access-Control-Allow-Headers", "accept, authorization, Content-Type");
put("Via", "1.1 vegur");
}};
return new WebResourceResponse("text/plain", "UTF-8", 200, "OK", headers, null);
}
}
然后在您的WebViewClient实现中调用它,如下所示:
@Override
@TargetApi(21)
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
return OptionsAllowResponse.build();
}
return null;
}
由于OPTIONS响应需要检查WebResourceRequest中请求的HTTP方法,而该方法只在API 21及以上版本中提供,因此仅适用于API级别21以上的版本。
HttpURLConnection
来获取文件数据并将其返回到WebResourceResponse
中。 - jcesarmobile