我有一个webview,我想要添加自定义标题,我希望这可以满足重定向并查看如何执行此操作,我偶然发现了最高投票答案here。
但是,此解决方案使用的是现已弃用的方法。我试图修改解决方案:
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类以满足即使是在webview上点击的链接,我想出了以下内容:
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");
以上不起作用,我无法确定原因 - 我得到一个空白的webview。当我从data
打印值时,我会得到一些未知字符。
答案 0 :(得分:0)
我也在尝试向Webview请求添加自定义标头,这就是我偶然发现您的问题的原因。我发现另一个问题解决了与an answer that worked for me类似的问题,所以它也可能会为你解决问题:
我有同样的问题。如果删除
urlConnection.disconnect();
它有效。