【问题标题】:Get content string (not source code) of webPage on Android在Android上获取网页的内容字符串(不是源代码)
【发布时间】:2013-01-10 12:44:14
【问题描述】:

我制作了一个 Javascript 页面来生成一个 JSON 对象,然后从 Android 设备读取它。 我用以下代码阅读它

StringBuilder stringBuilder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);

    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode == 200){
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null){
                stringBuilder.append(line);
            }
        } else {
            Log.e("JSON", "Failed to donwload file");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

问题是这段代码返回的是网页的源代码,而源代码是Javascript中的脚本,而不是执行后生成的JSON字符串。 我需要 JSON 字符串,并且需要使用 Javascript 生成 JSON 字符串,因为我访问的是外部服务。

我还没有找到任何解决方案。我不在乎可能的解决方案是否涉及服务器或 Android 终端。

谢谢。

【问题讨论】:

    标签: javascript android json


    【解决方案1】:
    String myresponse=Html.escapeHtml(YourStringHere);
    

    【讨论】:

    • 如果我转义 html 标签,我将一无所有,因为 JSON 对象是由 javascript(在客户端)生成的。我的意思是我只得到 javascript 源代码。问题是我没有得到 JSON 字符串。
    • 确保您使用的网址不会重定向到另一个网址。否则它将返回您的源代码而不是 JSON 字符串。
    【解决方案2】:

    试试这个。

    private class MyJavaScriptInterface {
    
         private MyJavaScriptInterface () {
          }
    
        public void setHtml(String contentHtml) {
    
                        //here you get the content html
        }
    }
    private WebViewClient webViewClient = new WebViewClient() {
    
    
     @Override
     public void onPageFinished(WebView view, String url) {
         view.loadUrl("javascript:window.ResponseChecker.setHtml"
                        + "(document.body.innerHTML);");
            }
     }
    

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 2017-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多