【问题标题】:Get Raw Http Source Code from WebView从 WebView 获取原始 Http 源代码
【发布时间】:2017-04-14 16:00:04
【问题描述】:
  1. 我正在与WebView 合作。现在我需要获取网页的来源。 我尝试过使用JavascriptInterface,但源受到javascript 的影响(当我在chrome 上使用“view-source:”时不一样)。
  2. 我们可以使用CookieWebViewOkHttp 吗?我已经登录 Google,我的 cookie 保存在 WebView,现在我想获取一些数据,但在 OkHttp 中而不是在 WebView 中。

【问题讨论】:

    标签: android webview okhttp3


    【解决方案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);
    }
    

    【讨论】:

    • 但我需要 WebView 的 cookie 才能访问该页面
    • 以及如何在 OkHttpClient(或任何客户端)上使用该 cookie?我想在页面上获取 HTML 的网站,只有在我登录后才能访问(我已经在 WebView 上登录)
    • 我不明白你的意思?您正在尝试将这些 cookie 转移到其他客户端吗?
    • 我想将 WebView 的 cookie 用于 OkHttpClient(或其他一些 http 客户端)
    猜你喜欢
    • 2021-12-16
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多