2014-12-24 3 views
1

내 웹보기가 특정 페이지 (예 : 잘못된 로그인 페이지)를로드하는 경우를 감지하고 싶습니다. 내가 onLoadResourceshouldOverrideUrlLoading을 사용해 보았지만 작동하지 못했습니다. 웹 페이지가로드 될 때마다 HTML을 구문 분석하고 HTML 내에 특정 문자열이있는 경우 더 나은 방법을 생각하고 있습니다. , 그럼 뭐든지해라.Webview의 HTML 내용을 구문 분석 - Android

이 방법이 있습니까? 나는 TagSoup를 사용하여 시도했지만, 나는 내 webview에 그것을 연관시키는 방법을 모른다. postUrl이 레이아웃에 사용자가 버튼을 클릭에서 시작됩니다 기본적으로

String fullpost = "pass=" + passwordt + "&user=" + usernamet + "&uuid=" + UUID; 

    String url = "mydomain.com"; 
     mWebview.postUrl(url, EncodingUtils.getBytes(fullpost, "BASE64")); 
     mWebview.setWebViewClient(new WebViewClient() { 

      public void onPageFinished(WebView mWebview, String url) { 
       String webUrl = mWebview.getUrl(); 
        if (webUrl.contains("/loginf")) { 
         MainActivity.this.mWebview.stopLoading(); 
         MainActivity.this.setContentView(R.layout.preweb); 

        } 
       } 
     }); 

, 그는 웹보기를 시작 무엇을하고 나는이 들어있는 레이아웃에 setContentView 전화 : 여기 내 코드는 지금의 모습입니다 webview.

거기에서 로그인 정보가 맞으면 웹 페이지가 XXX로 이동하고 올바르지 않으면 YYY로 이동합니다. 따라서 YYY가로드되면 즉시 (그리고 모든 페이지로드시에) YYY가로드되면 즉시 검색하고 싶습니다. //domagic. 희망은 그 말이 맞습니다. url에서 XXX 또는 YYY로 리디렉션되는 페이지는 자동으로 사용자가 시작하지 않으며 shouldOverrideUrlLoading이 작동하지 않으며 onLoadResource을 사용하는 방법을 알 수 없으므로 완전히 손실됩니다.

현재 나의 생각은 모든 것을 별도의 스레드로로드 한 다음 WebView를 사용하여 내용을 표시합니다 (HTML을 구문 분석 할 수있는 방식으로). 그러나 어떻게 작동하는지, 또는 어떻게 수행할지 모르겠습니다. .

누구나 아이디어 나 제안이 있으십니까?

답변

0

나는 웹뷰 내용의 텍스트 문자열을 얻는 방법을 읽었다 고 생각한다. 그런 다음 jsoup를 사용하여 구문 분석 할 수 있습니다. [neh, 심지어 jsoup 필요가 없습니다. indexOf string check]

HTTP 클라이언트로 로그인을 처리하는 것이 좋습니다. 그것은 당신에게 유연성을 제공하며 더 적절한 방법으로 보입니다. 나는 HTTP get 및 post 요청을 위해 loopj 라이브러리를 사용 해왔다. 단순한 코드가 가능합니다. 어쨌든 나를 위해, 상대적으로 안드로이드 초보자. 내 프로젝트에서 얻은 몇 가지 코드가 있습니다. 진행률 표시 줄 및 쿠키 관리 같은 것을 생략했습니다.

private void loginFool() { 
    String urlString = "http://www.example.com/login/"; 

    // username & password 
    RequestParams params = new RequestParams(); 
    params.put("username", username.getText().toString()); 
    params.put("password", password.getText().toString()); 

    // send the request 
    loopjClient.post(urlString, params, new TextHttpResponseHandler() { 

     @Override 
     public void onStart() { 
      // called before request is started 
      //System.err.println("Starting..."); 
     } 

     @Override 
     public void onSuccess(int statusCode, Header[] headers, String responseString) { 
      // called when response HTTP status is "200 OK" 

      // see if 'success' was a failed login... 
      int idx = responseString.indexOf("Please try again!"); 
      if(idx > -1) { 
       makeMyToast("Sorry, login failed!"); 
      } 
      // or actual success-ful login 
      else { 

       // manage cookies here 

       // put extractData in separate thread 
       final String responseStr = responseString; 
       new Thread(new Runnable() { 
        public void run(){ 

         extractData(responseStr); 
         selectData(defaultPrefs.getInt("xyz_display_section", 0)); 

         // start the next activity 
         Intent intent = new Intent(MainActivity.this, PageViewActivity.class); 
         startActivity(intent); 
         finish(); 

        } 
       }).start(); 

      } 
     } 

     @Override 
     public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { 
      // called when response HTTP status is "4XX" (eg. 401, 403, 404) 

      makeMyToast("Whoops, network error!"); 
     } 

     @Override 
     public void onFinish() { 
      // done 
     } 

    }); 
} 

당신은 onFailure 콜백에서, 내가 네트워크 오류 메시지를주고 응답 핸들러의는 onSuccess 콜백에서, 내가 로그인이 실패하는지, 문자열을 테스트 할 수 있습니다, 그것을 참조 할 수 있습니다.

나는이 유형의 포스트 로그인이 작동하는 웹 서버의 비율을 알만큼 충분히 경험이 없습니다.

loopj 클라이언트는 쿠키를 수신하고 관리합니다. webview를 통해 사이트의 페이지에 액세스하는 경우 loopj 클라이언트의 쿠키를 webview로 복사해야합니다.

private AsyncHttpClient loopjClient = new AsyncHttpClient(); 
private PersistentCookieStore xyzCookieStore; 

xyzCookieStore = new PersistentCookieStore(this); 
loopjClient.setCookieStore(Utility.xyzCookieStore); 
: I 클래스 변수 정의 및 초기화를 포함해야, 그리고 :

// get cookies from the generic http session, and copy them to the webview 
CookieSyncManager.createInstance(getApplicationContext()); 
CookieManager.getInstance().removeAllCookie(); 
CookieManager cookieManager = CookieManager.getInstance(); 

List<Cookie> cookies = xyzCookieStore.getCookies(); 
for (Cookie eachCookie : cookies) { 
    String cookieString = eachCookie.getName() + "=" + eachCookie.getValue(); 
    cookieManager.setCookie("http://www.example.com", cookieString); 
    //System.err.println(">>>>> " + "cookie: " + cookieString); 
} 
CookieSyncManager.getInstance().sync(); 
// holy crap, it worked; I am automatically logged in, in the webview 

편집 : 나는 그렇게 몇 온라인 게시물에서 코드를 자갈길