4

我正在尝试使用人行横道嵌入式 webview 来显示网页,并带有一些 javascript。因为我需要为每个请求添加一些标头,所以我使用 拦截请求shouldInterceptLoadRequest,并使用 OkHttp 发出请求。

@Override
public WebResourceResponse shouldInterceptLoadRequest(XWalkView view, String url) {
    try {
        Log.i(App.TAG, url);
        return new WebResourceResponse("", "UTF-8", getUrl(url));
    } catch (Exception e) {
        e.printStackTrace();
        return super.shouldInterceptLoadRequest(view, url);
    }
}

InputStream getUrl(String url) throws IOException {
    Request request = new Request.Builder()
            .url(url)
            .addHeader("MyHeader","MyHeaderValue")
            .build();

    Response response = client.newCall(request).execute();

    return response.body().byteStream();
}

此代码一开始按预期工作,但在发出 Ajax 请求时,我收到此错误:[INFO:CONSOLE(0)] "XMLHttpRequest cannot load https://api.example1.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example2.com' is therefore not allowed access."

如果我不拦截请求,我不会收到此错误,但是我失去了向请求添加标头的能力。

4

0 回答 0