我尝试进行基本身份验证以查看受保护的网址。 我正在使用令牌对URL进行GET请求。当我尝试使用HttpUrlConnection后,在webview显示空白后
我试过两种方式:
1
WebViewClient webViewClient = new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url1) {
try {
URL url = new URL(url1);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
CookieManager cookieManager = CookieManager.getInstance();
String cookie = cookieManager.getCookie(url.getHost());
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Cookie", cookie);
urlConnection.setRequestProperty("CRM_USER_AGENT", "crm_app");
urlConnection.setRequestMethod("GET");
urlConnection.addRequestProperty("Authorization", "Bearer "+token);
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;
}
}
};
webView.setWebViewClient(webViewClient);
webView.setVisibility(View.INVISIBLE);
webView.setVisibility(View.VISIBLE);
webView.loadUrl(urlAddress);
和2:
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, null);
webview = (WebView) view.findViewById(R.id.webview);
mySingleton = MySingleton.getInstance(getActivity());
final String token = "Bearer " + mySingleton.getData(Constant.GUEST_TOKEN);
webview.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
urlAddress = url;
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Authorization", token);
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.setVisibility(View.INVISIBLE);
webview.setVisibility(View.VISIBLE);
webview.loadUrl(urlAddress);
return view;
}
但无法获得成功并显示空白。
如何通过身份验证和显示网页后实现GET请求的响应?