【问题标题】:Running javascript in an android app?在android应用程序中运行javascript?
【发布时间】:2013-05-11 08:06:42
【问题描述】:

有一个网站提供了一些 javascript 来发出我需要的信息,有没有办法通过 androids API 来使用这个 javascript 发出它拥有的任何信息并通过它解析?

这是javascript:

<script type="text/javascript" src="http://pulllist.comixology.com/js/pulllist/5b467b28e73595311e02fe32c3081e4a.js?date=2013-05-15"></script>

如果您在 html 文件中运行它,您会注意到它会显示从网站检索到的图像和文本,我想在一个 android 应用程序中获取所有这些信息。

【问题讨论】:

  • 答案用安卓代码编辑!

标签: java javascript android html web


【解决方案1】:

我不知道你是否可以直接运行 javascript 代码,但你可以在 webview 中运行它(可能是隐藏的?)并使用 javascript 接口拦截 javascript 调用,结合注入 webview 我想你应该能够做几乎所有你想做的事情。 如果您需要它,您还可以下载 js 源代码,根据需要对其进行解析,然后将其提供给 webview。如果您想了解更多信息,请告诉我^^

无论如何,网络上到处都是例子,这里是 exampleanother one

编辑
好的,你不需要实际运行那个 javascript,解析它就足够了,这里是一个在 android 中实现 @T.S. 的工作示例。解析方法,要运行它,您只需将 android.permission.INTERNET 添加到您的清单文件并设置一个带有 myTextView id 的 textview。

public class MainActivity extends Activity implements Runnable{
    TextView myTextView;

    public Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){

            String source = (String)msg.obj;                        
            // The index of the item
            int i = 0;

            // We search the data-string from the start
            int position1 = 0;

            // While there are items found, continue
            while(true) {

                // Look for the pattern a[index]={json data};
                String lookFor1 = "a[" + String.valueOf(i) + "]={";
                String lookFor2 = "};";
                position1  = source.indexOf(lookFor1, position1+1);

                // Check if we have a match
                if(position1 > -1) {

                    // Find the end of the match
                    int position2 = source.indexOf(lookFor2, position1);

                    // Get the result
                    String result = source.substring(position1 + lookFor1.length() - 1, position2 + 1);

                    // Increase the index an check if we can find a next item
                    i++;

                    // Print out this row, which is a JSON representation of the data you want
                    Log.e("res",result);
                    try {
                        JSONObject obj = new JSONObject(result);
                        String title = obj.getString("title");
                        String img = obj.getString("img");
                        String src = new JSONObject(img).getString("src");
                        myTextView.append("\ntitle: "+title+"\nimgurl: "+src+"\n");
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                } else {
                    // We haven't found a match, break out of while loop
                    break;
                }
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myTextView = (TextView) findViewById(R.id.myTextView);

        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void run() {
        String data = retrieve_data();
        Message msg = handler.obtainMessage();
        msg.obj = data;
        handler.sendMessage(msg);

    }

    private String retrieve_data(){

        String data = "";
        String url = "http://pulllist.comixology.com/js/pulllist/5b467b28e73595311e02fe32c3081e4a.js?date=2013-05-15";
        HttpClient httpclient = new DefaultHttpClient();

        HttpGet request;
        try {
            request = new HttpGet(new URI(url));
            request.addHeader("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:21.0) Gecko/20100101 Firefox/21.0");

            HttpResponse response = httpclient.execute(request);
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                data = out.toString();
            }
        } catch (URISyntaxException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }



}

【讨论】:

    【解决方案2】:

    如果只是为了显示,您可以使用带有一些自定义样式的WebView。 链接:http://developer.android.com/reference/android/webkit/WebView.html

    String html = "<script type='text/javascript' src='http://pulllist.comixology.com/js/pulllist/5b467b28e73595311e02fe32c3081e4a.js?date=2013-05-15'></script>";
    String mime = "text/html";
    String encoding = "utf-8";
    
    WebView myWebView = (WebView)this.findViewById(R.id.myWebView);
    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.loadDataWithBaseURL(null, html, mime, encoding, null);
    

    更新

    我写了一个快速而肮脏的示例,说明如何从该 javascript 文件中提取数据:

    import java.util.*;
    import java.lang.*;
    import java.net.*;
    import java.io.*;
    
    public class JavascriptToUsableData {
    
        // Method to get a string from an URL
        // Thanks to http://stackoverflow.com/a/4328733/1226267
        public static String getText(String url) throws Exception {
            URL website = new URL(url);
            URLConnection connection = website.openConnection();
            BufferedReader in = new BufferedReader(
                                    new InputStreamReader(
                                        connection.getInputStream()));
    
            StringBuilder response = new StringBuilder();
            String inputLine;
    
            while ((inputLine = in.readLine()) != null) 
                response.append(inputLine);
    
            in.close();
    
            return response.toString();
        }
    
        public static void main (String args[]) throws Exception {
    
            // Get the data
            String source = JavascriptToUsableData.getText("http://pulllist.comixology.com/js/pulllist/5b467b28e73595311e02fe32c3081e4a.js?date=2013-05-15");
    
            // The index of the item
            int i = 0;
    
            // We search the data-string from the start
            int position1 = 0;
    
            // While there are items found, continue
            while(true) {
    
                // Look for the pattern a[index]={json data};
                String lookFor1 = "a[" + String.valueOf(i) + "]={";
                String lookFor2 = "};";
                position1  = source.indexOf(lookFor1, position1+1);
    
                // Check if we have a match
                if(position1 > -1) {
    
                    // Find the end of the match
                    int position2 = source.indexOf(lookFor2, position1);
    
                    // Get the result
                    String result = source.substring(position1 + lookFor1.length() - 1, position2 + 1);
    
                    // Increase the index an check if we can find a next item
                    i++;
    
                    // Print out this row, which is a JSON representation of the data you want
                    System.out.println(result);
    
                    // I'm not in an Android environment right now, but there is a JSON reader you can use in Android
                    // I think it works somthing like this:
                    // resultObj = new JSONObject(result);
    
                    // And then access the data like this:
                    // resultObj.getString("title");
                    // resultObj.getString("guid");
                    // resultObj.getString("img");
                    // etc
    
                } else {
                    // We haven't found a match, break out of while loop
                    break;
                }
            }
        }
    }
    

    它可以进行很多优化,并且在当前状态下可能不是故障安全的,但它可能会给你一些关于如何开始的提示。

    【讨论】:

    • 不幸的是它不仅仅是为了显示,我需要抓取图像文件和文本数据并将它们设置到androids控件中......
    • comixology 网站是否提供任何其他方式来提供此数据?喜欢 XML?
    • 我用一个简单的例子来更新我的答案,说明如何实现你的目标。
    猜你喜欢
    • 2014-08-05
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 2014-08-28
    • 2023-03-22
    • 2015-03-02
    相关资源
    最近更新 更多