- 我正在使用
WebView
。现在,我需要获取网页的来源。我已经尝试使用JavascriptInterface
,但是来源受到javascript
的影响(当我使用" view-source:"在chrome上)。 - 我们可以使用从
WebView
到OkHttp
的Cookie
吗?我已经登录了Google,我的cookie保存在WebView
中,现在我想获取一些数据,但在OkHttp
中不在WebView
中。
您可以通过DefaultHttpClient
as:
HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client
HttpGet httpget = new HttpGet("http://yoururl.com"); // Set the action you want to do
HttpResponse response = httpclient.execute(httpget); // Executeit
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent(); // Create an InputStream with the response
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) // Read line by line
sb.append(line + "n");
String resString = sb.toString(); // Result is here
is.close(); // Close the stream
您还必须添加一些超时参数:
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,3000); // 3s max for connection
HttpConnectionParams.setSoTimeout(httpParameters, 4000); // 4s max to get data
HttpClient httpclient = new DefaultHttpClient(httpParameters);
编辑:
您可以从WebView获取cookie:
@Override
public void onPageFinished(WebView view, String url){
String cookies = CookieManager.getInstance().getCookie(url);
Log.d(TAG, "All the cookies in a string:" + cookies);
}