我有一个 Web 视图,我想在其中添加自定义标头,我希望它迎合重定向并查看如何做到这一点,我偶然发现了这里投票最高的答案。
但是,此解决方案使用的是现已弃用的方法。我试图修改解决方案:
public void webViewUrlConn() {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("https://someUrl.com");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
CookieManager cookieManager = CookieManager.getInstance();
String cookie = cookieManager.getCookie(url.getHost());
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Cookie", cookie);
urlConnection.setRequestProperty("CRM_USER_AGENT", "crm_app");
urlConnection.setRequestMethod("POST");
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
data = new java.util.Scanner(in).useDelimiter("\A").next();
System.out.println("Data:" + data);
urlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
public void run() {
wv.loadData(data, "text/html", "UTF-8");
pd.setVisibility(View.INVISIBLE);
wv.setVisibility(View.VISIBLE);
}
});
}
}).start();
}
这完美无缺。但这不是我需要的。我想重写 WebViewClient 类以满足在 Web 视图上单击的链接,我想出了以下内容:
WebViewClient webViewClient = new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url1) {
try {
URL url = new URL(url1);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
CookieManager cookieManager = CookieManager.getInstance();
String cookie = cookieManager.getCookie(url.getHost());
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Cookie", cookie);
urlConnection.setRequestProperty("CRM_USER_AGENT", "crm_app");
urlConnection.setRequestMethod("POST");
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
data = new java.util.Scanner(in).useDelimiter("\A").next();
System.out.println("Data:" + data);
urlConnection.getContentType();
urlConnection.getContentEncoding();
urlConnection.getContentEncoding();
urlConnection.disconnect();
return new WebResourceResponse("text/html","UTF-8", in);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
};
wv.setWebViewClient(webViewClient);
pd.setVisibility(View.INVISIBLE);
wv.setVisibility(View.VISIBLE);
wv.loadUrl("https://someurl.com");
以上不起作用,我无法确定原因 - 我得到一个空白的 Web 视图。 当我打印data
的值时,我得到一些未知字符。
我还在尝试向 Webview 请求添加自定义标头,这就是我偶然发现您的问题的原因。我发现了另一个问题,用一个对我有用的答案来解决类似的问题,所以它也可能为你解决问题:
我有同样的问题。如果删除
urlConnection.disconnect();
它有效。