我需要向来自WebView的每个请求添加自定义标头。我知道loadURL
具有的参数extraHeaders
,但这些参数仅应用于初始请求。所有后续请求均不包含标头。我已经看过所有的替代WebViewClient
,但是没有什么允许向资源请求添加标头- onLoadResource(WebView view, String url)
。任何帮助都会很棒。
谢谢,雷
我需要向来自WebView的每个请求添加自定义标头。我知道loadURL
具有的参数extraHeaders
,但这些参数仅应用于初始请求。所有后续请求均不包含标头。我已经看过所有的替代WebViewClient
,但是没有什么允许向资源请求添加标头- onLoadResource(WebView view, String url)
。任何帮助都会很棒。
谢谢,雷
Answers:
尝试
loadUrl(String url, Map<String, String> extraHeaders)
要将标头添加到资源加载请求中,请定制WebViewClient并重写:
API 24+:
WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request)
or
WebResourceResponse shouldInterceptRequest(WebView view, String url)
view.loadUrl("http://www.facebook.com", extraHeaders)
,有'http://static.fb.com/images/logo.png'
从webiew发送的多个资源请求(例如etc)。对于这些请求,不添加额外的标题。并且在此类资源请求期间不调用shouldOverrideUrlLoading。调用了“ OnLoadResource”回调,但是目前无法设置标头。
shouldInterceptRequest
方法实现,请解释一下如何?
您将需要使用WebViewClient.shouldInterceptRequest拦截每个请求
每次拦截时,您都需要获取url,自己提出此请求,然后返回内容流:
WebViewClient wvc = new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("MY-CUSTOM-HEADER", "header value");
httpGet.setHeader(HttpHeaders.USER_AGENT, "custom user-agent");
HttpResponse httpReponse = client.execute(httpGet);
Header contentType = httpReponse.getEntity().getContentType();
Header encoding = httpReponse.getEntity().getContentEncoding();
InputStream responseInputStream = httpReponse.getEntity().getContent();
String contentTypeValue = null;
String encodingValue = null;
if (contentType != null) {
contentTypeValue = contentType.getValue();
}
if (encoding != null) {
encodingValue = encoding.getValue();
}
return new WebResourceResponse(contentTypeValue, encodingValue, responseInputStream);
} catch (ClientProtocolException e) {
//return null to tell WebView we failed to fetch it WebView should try again.
return null;
} catch (IOException e) {
//return null to tell WebView we failed to fetch it WebView should try again.
return null;
}
}
}
Webview wv = new WebView(this);
wv.setWebViewClient(wvc);
如果您的最低API目标是21级,则可以使用新的shouldInterceptRequest,它为您提供其他请求信息(例如标头),而不仅仅是URL。
public WebResourceResponse shouldInterceptRequest (WebView view, WebResourceRequest request)
而是在此处
也许我的回复很晚了,但它涵盖了API 之上和之下的内容 21水平。
要添加标题,我们应该拦截每个请求并创建一个新请求使用所需的标题。
因此,我们都需要重写在两种情况下调用的shouldInterceptRequest方法:1.对于API,直到级别21;2.适用于21级以上的API
webView.setWebViewClient(new WebViewClient() {
// Handle API until level 21
@SuppressWarnings("deprecation")
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
return getNewResponse(url);
}
// Handle API 21+
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
return getNewResponse(url);
}
private WebResourceResponse getNewResponse(String url) {
try {
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url.trim())
.addHeader("Authorization", "YOU_AUTH_KEY") // Example header
.addHeader("api-key", "YOUR_API_KEY") // Example header
.build();
Response response = httpClient.newCall(request).execute();
return new WebResourceResponse(
null,
response.header("content-encoding", "utf-8"),
response.body().byteStream()
);
} catch (Exception e) {
return null;
}
}
});
如果应处理响应类型,则可以更改
return new WebResourceResponse(
null, // <- Change here
response.header("content-encoding", "utf-8"),
response.body().byteStream()
);
至
return new WebResourceResponse(
getMimeType(url), // <- Change here
response.header("content-encoding", "utf-8"),
response.body().byteStream()
);
并添加方法
private String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
switch (extension) {
case "js":
return "text/javascript";
case "woff":
return "application/font-woff";
case "woff2":
return "application/font-woff2";
case "ttf":
return "application/x-font-ttf";
case "eot":
return "application/vnd.ms-fontobject";
case "svg":
return "image/svg+xml";
}
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
如前所述,您可以执行以下操作:
WebView host = (WebView)this.findViewById(R.id.webView);
String url = "<yoururladdress>";
Map <String, String> extraHeaders = new HashMap<String, String>();
extraHeaders.put("Authorization","Bearer");
host.loadUrl(url,extraHeaders);
我对此进行了测试,然后使用MVC控制器对其进行了扩展,该控制器扩展了Authorize Attribute以检查标头和标头是否存在。
这对我有用:
首先,您需要创建方法,该方法将返回要添加到请求的标头:
private Map<String, String> getCustomHeaders()
{
Map<String, String> headers = new HashMap<>();
headers.put("YOURHEADER", "VALUE");
return headers;
}
其次,您需要创建WebViewClient:
private WebViewClient getWebViewClient()
{
return new WebViewClient()
{
@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
{
view.loadUrl(request.getUrl().toString(), getCustomHeaders());
return true;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url, getCustomHeaders());
return true;
}
};
}
将WebViewClient添加到您的WebView:
webView.setWebViewClient(getWebViewClient());
希望这可以帮助。
loadUrl(String url, Map<String, String> additionalHttpHeaders)
意味着添加附加标题
您应该能够通过跳过loadUrl并使用Java的HttpURLConnection编写自己的loadPage来控制所有标头。然后使用网络视图的loadData显示响应。
无法访问Google提供的标题。它们在WebView源代码的JNI调用中。
这是使用HttpUrlConnection的实现:
class CustomWebviewClient : WebViewClient() {
private val charsetPattern = Pattern.compile(".*?charset=(.*?)(;.*)?$")
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
try {
val connection: HttpURLConnection = URL(request.url.toString()).openConnection() as HttpURLConnection
connection.requestMethod = request.method
for ((key, value) in request.requestHeaders) {
connection.addRequestProperty(key, value)
}
connection.addRequestProperty("custom header key", "custom header value")
var contentType: String? = connection.contentType
var charset: String? = null
if (contentType != null) {
// some content types may include charset => strip; e. g. "application/json; charset=utf-8"
val contentTypeTokenizer = StringTokenizer(contentType, ";")
val tokenizedContentType = contentTypeTokenizer.nextToken()
var capturedCharset: String? = connection.contentEncoding
if (capturedCharset == null) {
val charsetMatcher = charsetPattern.matcher(contentType)
if (charsetMatcher.find() && charsetMatcher.groupCount() > 0) {
capturedCharset = charsetMatcher.group(1)
}
}
if (capturedCharset != null && !capturedCharset.isEmpty()) {
charset = capturedCharset
}
contentType = tokenizedContentType
}
val status = connection.responseCode
var inputStream = if (status == HttpURLConnection.HTTP_OK) {
connection.inputStream
} else {
// error stream can sometimes be null even if status is different from HTTP_OK
// (e. g. in case of 404)
connection.errorStream ?: connection.inputStream
}
val headers = connection.headerFields
val contentEncodings = headers.get("Content-Encoding")
if (contentEncodings != null) {
for (header in contentEncodings) {
if (header.equals("gzip", true)) {
inputStream = GZIPInputStream(inputStream)
break
}
}
}
return WebResourceResponse(contentType, charset, status, connection.responseMessage, convertConnectionResponseToSingleValueMap(connection.headerFields), inputStream)
} catch (e: Exception) {
e.printStackTrace()
}
return super.shouldInterceptRequest(view, request)
}
private fun convertConnectionResponseToSingleValueMap(headerFields: Map<String, List<String>>): Map<String, String> {
val headers = HashMap<String, String>()
for ((key, value) in headerFields) {
when {
value.size == 1 -> headers[key] = value[0]
value.isEmpty() -> headers[key] = ""
else -> {
val builder = StringBuilder(value[0])
val separator = "; "
for (i in 1 until value.size) {
builder.append(separator)
builder.append(value[i])
}
headers[key] = builder.toString()
}
}
}
return headers
}
}
请注意,这不适用于POST请求,因为WebResourceRequest不提供POST数据。有一个请求数据-WebViewClient库,它使用JavaScript注入替代方法来拦截POST数据。
这对我有用。像下面这样创建WebViewClient并将webclient设置为您的webview。我必须使用webview.loadDataWithBaseURL,因为我的网址(在我的内容中)没有基本网址,而只有相对网址。仅当使用loadDataWithBaseURL设置了baseurl时,您才能正确获取该url。
public WebViewClient getWebViewClientWithCustomHeader(){
return new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
OkHttpClient httpClient = new OkHttpClient();
com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
.url(url.trim())
.addHeader("<your-custom-header-name>", "<your-custom-header-value>")
.build();
com.squareup.okhttp.Response response = httpClient.newCall(request).execute();
return new WebResourceResponse(
response.header("content-type", response.body().contentType().type()), // You can set something other as default content-type
response.header("content-encoding", "utf-8"), // Again, you can set another encoding as default
response.body().byteStream()
);
} catch (ClientProtocolException e) {
//return null to tell WebView we failed to fetch it WebView should try again.
return null;
} catch (IOException e) {
//return null to tell WebView we failed to fetch it WebView should try again.
return null;
}
}
};
}
我遇到了同样的问题并解决了。
如前所述,您需要创建自定义WebViewClient并覆盖shouldInterceptRequest方法。
WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request)
该方法应在返回“空” WebResourceResponse的同时发出webView.loadUrl。
像这样:
@Override
public boolean shouldInterceptRequest(WebView view, WebResourceRequest request) {
// Check for "recursive request" (are yor header set?)
if (request.getRequestHeaders().containsKey("Your Header"))
return null;
// Add here your headers (could be good to import original request header here!!!)
Map<String, String> customHeaders = new HashMap<String, String>();
customHeaders.put("Your Header","Your Header Value");
view.loadUrl(url, customHeaders);
return new WebResourceResponse("", "", null);
}
用这个:
webView.getSettings().setUserAgentString("User-Agent");