2013-05-16 1 views
3

내가 필요로하는 정보를 방출하는 자바 스크립트를 제공하는 웹 사이트가 있습니다. 안드로이드 API를 통한 방법이 있으며,이 자바 스크립트를 사용하여 정보를 내보내고 파싱합니다.Android 앱에서 자바 스크립트를 실행 하시겠습니까?

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

당신이 HTML 파일을 실행하면 당신이 이미지를 표시 통지하고 웹 사이트에서 검색 텍스트거야, 내가 모든 정보를 얻을 싶습니다

은 자바 스크립트입니다 android app.

+0

답변은 android code! – lelloman

답변

1

그냥 표시하기 위해 사용자 정의 스타일로 WebView을 사용할 수 있습니다. 링크 : 그것은 많은 최적화 할 수 있습니다

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

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

업데이트

나는 자바 스크립트 파일에 해당로부터 데이터를 추출 할 수있는 방법에 대한 신속하고 더러운 예를 썼다 아마도 현재 상태에서는 훼일 세이프가 아니지만 시작하는 방법에 대한 힌트를 줄 수 있습니다.

+0

안타깝게도 단지 표시하는 것이 아니라 이미지 파일과 텍스트 데이터를 가져 와서 안드로이드 컨트롤로 설정해야합니다 ... – tweetypi

+0

만화 웹 사이트는이 데이터를 제공하는 다른 방법을 제공합니까? XML처럼? –

+0

그저 실망스러운 자바 스크립트가 아닐뿐 ... – tweetypi

2

자바 스크립트 코드를 직접 실행할 수 있는지는 모르지만 webview (숨겨진 코드 일 수도 있습니다)에서 실행하고 자바 스크립트 인터페이스를 사용하여 자바 스크립트 호출을 가로 챌 수 있습니다. 당신은 당신이 원하는 거의 모든 것을 할 수 있어야합니다. 필요한 경우 js 소스를 다운로드하고 원하는대로 파싱 한 다음 webview에 피드를 제공 할 수 있습니다. 당신이 더 많은 것을 원하는 경우에 정보 나 웹 여기에, 어쨌든 exampleanother one

편집 예 가득합니다 ^^

을 알려
당신이 그것을 구문 분석, 실제로 자바 스크립트를 실행할 필요가 없습니다 확인 충분하다. @TS를 구현 한 안드로이드의 실제 예가 여기에있다. 구문 분석 방법을 사용하려면 실행하려면 android.permission.INTERNET을 매니페스트 파일에 추가하고 myTextView ID가 설정된 텍스트 뷰가 있어야합니다.

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



} 
관련 문제