1
我有一個webview我想添加自定義標題,我想這個以迎合重定向,看着如何做到這一點,我偶然發現最高投票回答here。與HttpUrlConnection自定義WebViewClient - 爲每個請求(WebView)添加標頭
但是,此解決方案正在使用現在已棄用的方法。我試圖修改解決方案:
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");
以上不工作,我不能確定爲什麼 - 我得到一個空白網頁視圖。當我打印data
的值時,我會看到一些未知的字符。
*我得到一個空白網頁視圖。*,因爲掃描儀消費流*,當我從數據打印值*也許服務器使用的是壓縮... – Selvin
我將與評論的掃描儀檢查,我沒有意識到這一點'消費'數據,並使我的'in'變量不可用。就壓縮而言,我認爲其他代碼示例應該也是這種情況,但它的工作完美無瑕。 – User3