从WebView获取原始Http源代码

时间:2016-11-30 10:55:30

标签: android webview okhttp3

  1. 我正在使用WebView。现在我需要获取网页的来源。 我尝试使用JavascriptInterface,但来源已受javascript影响(在Chrome上使用“view-source:”时不一样)。
  2. 我们可以使用CookieWebView的{​​{1}}吗?我已登录Google,我的Cookie已保存在OkHttp,现在我想获取一些数据但WebView不在OkHttp

1 个答案:

答案 0 :(得分:-1)

您可以通过DefaultHttpClient

点击网址来获取它

为:

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);
}