IT

웹뷰에서 HTML 콘텐츠를 얻는 방법?

lottoking 2020. 8. 2. 17:12
반응형

웹뷰에서 HTML 콘텐츠를 얻는 방법?


웹뷰에서 HTML 코드를 얻는 가장 간단한 방법은 무엇입니까? stackoverflow 및 Google에서 여러 가지 방법을 시도했지만 정확한 방법을 수 없습니다. 정확한 방법을 참조하십시오.

public class htmldecoder extends Activity implements OnClickListener,TextWatcher
{
TextView txturl;
Button btgo;
WebView wvbrowser;
TextView txtcode;
ImageButton btcode;
LinearLayout llayout;
int flagbtcode;
public void onCreate(Bundle savedInstanceState)
{
            super.onCreate(savedInstanceState);
                setContentView(R.layout.htmldecoder);

    txturl=(TextView)findViewById(R.id.txturl);

    btgo=(Button)findViewById(R.id.btgo);
    btgo.setOnClickListener(this);

    wvbrowser=(WebView)findViewById(R.id.wvbrowser);
    wvbrowser.setWebViewClient(new HelloWebViewClient());
    wvbrowser.getSettings().setJavaScriptEnabled(true);
    wvbrowser.getSettings().setPluginsEnabled(true);
    wvbrowser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    wvbrowser.addJavascriptInterface(new MyJavaScriptInterface(),"HTMLOUT");
    //wvbrowser.loadUrl("http://www.google.com");
    wvbrowser.loadUrl("javascript:window.HTMLOUT.showHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");


    txtcode=(TextView)findViewById(R.id.txtcode);
    txtcode.addTextChangedListener(this);

    btcode=(ImageButton)findViewById(R.id.btcode);
    btcode.setOnClickListener(this);

    }

public void onClick(View v)
{
    if(btgo==v)
    {
        String url=txturl.getText().toString();
        if(!txturl.getText().toString().contains("http://"))
        {
            url="http://"+url;
        }
        wvbrowser.loadUrl(url);
        //wvbrowser.loadData("<html><head></head><body><div style='width:100px;height:100px;border:1px red solid;'></div></body></html>","text/html","utf-8");
    }
    else if(btcode==v)
    {
        ViewGroup.LayoutParams params1=wvbrowser.getLayoutParams();
        ViewGroup.LayoutParams params2=txtcode.getLayoutParams();
        if(flagbtcode==1)
        {
            params1.height=200;
            params2.height=220;
            flagbtcode=0;
            //txtcode.setText(wvbrowser.getContentDescription());
        }
        else
        {
            params1.height=420;
            params2.height=0;
            flagbtcode=1;
        }
        wvbrowser.setLayoutParams(params1);
        txtcode.setLayoutParams(params2);

    }
}

public class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        view.loadUrl(url);
        return true;
    }
    /*@Override
    public void onPageFinished(WebView view, String url)
    {
        // This call inject JavaScript into the page which just finished loading. 
        wvbrowser.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
    }*/

}
class MyJavaScriptInterface
{
    @SuppressWarnings("unused")
    public void showHTML(String html)
    {

        txtcode.setText(html);
    }
}

public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub

}

public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
    // TODO Auto-generated method stub

}

public void onTextChanged(CharSequence s, int start, int before, int count) {
    wvbrowser.loadData("<html><div"+txtcode.getText().toString()+"></div></html>","text/html","utf-8");

}

}

실제로이 질문에는 많은 답변이 있습니다. 그중 2 개는 다음과 가변합니다.

  • 첫 번째는 당신과 거의 동일합니다. 같은 튜토리얼에서 얻을 것입니다.

public class TestActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);
        final WebView webview = (WebView) findViewById(R.id.browser);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");

        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                webview.loadUrl("javascript:window.HtmlViewer.showHTML" +
                        "('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
            }
        });

        webview.loadUrl("http://android-in-action.com/index.php?post/" +
                "Common-errors-and-bugs-and-how-to-solve-avoid-them");
    }

    class MyJavaScriptInterface {

        private Context ctx;

        MyJavaScriptInterface(Context ctx) {
            this.ctx = ctx;
        }

        public void showHTML(String html) {
            new AlertDialog.Builder(ctx).setTitle("HTML").setMessage(html)
                    .setPositiveButton(android.R.string.ok, null).setCancelable(false).create().show();
        }

    }
}

이렇게하면 자바 펼쳐보기를 통해 HTML을 가져옵니다. Javascript 인터페이스가 있으면 다른 방법으로 추가 할 수 있습니다.


  • 다른 방법은 거기 와 같은 HttpClient를 사용하는 입니다.

선택하는 옵션은 검색 된 HTML로 수행하려는 작업에 따라 증가합니다.


Android 4.2의 경우 모든 Javasscript 함수에 @JavascriptInterface를 추가하는 것을 잊지 마세요


KitKat 이상에서는 evaluateJavascriptwebview에서 메소드를 사용할 수 있습니다.

wvbrowser.evaluateJavascript(
        "(function() { return ('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>'); })();",
         new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String html) {
                Log.d("HTML", html); 
                // code here
            }
    });

더 많은 예를 보려면 답변을 참조하십시오


Android WebView는 Chrome 또는 FireFox와 같이 HTTP 서버에서 다운로드 한 HTML 컨텐츠를 여러 가지 다른 렌더 엔진입니다. WebView에서 된 페이지 (또는 스크린 샷)를 가져와야하는 이유를 모르겠습니다. 대부분의 상황에서 이것이 필요하지 않습니다. HTTP 서버에서 항상 원시 HTML 컨텐츠를 직접 수 있습니다.

HttpUrlConnection 또는 HttpClient를 사용하여 원시 스트림을 통해 이미 게시 된 답변이 있습니다. 또는 Android에서 HTML 컨텐츠 구문 분석 / 프로세스를 처리 할 때 매우 편리한 라이브러리가 있습니다. JSoup , HTML 컨텐츠를 HTTP 서버에서 가져 오는 매우 간단한 API를 제공하고 HTML 구문 분석을 관리하는 데 도움이되는 HTML 문서의 추상 표현을 제공합니다. 보다 OO 스타일이지만 훨씬 쉽게 :

// Single line of statement to get HTML document from HTTP server.
Document doc = Jsoup.connect("http://en.wikipedia.org/").get();

예를 들어 HTML 문서를 먼저 다운로드 한 다음 언어를 위해 WebView에 전달하기 전에 일부 사용자 정의 CSS 또는 자바 확장을 추가하려는 경우에 편리합니다. 공식 웹 사이트에서 훨씬 더 많은 것을 확인할 수 있습니다.


Proguard 구성에서 제자리에 배치해야하는 하나의 접점이 "숨겨져"있습니다. 더 이상 작동하지 않을 때 HTML 리더가 자바 펼쳐 인터페이스를 통해 인터페이스 앱 구성 파일에 다음과 같이 작동하지 않을 때 HTML 리더가 더 이상 작동하지 않습니다.

-keepclassmembers class <your.fully.qualified.HTML.reader.classname.here> {
    public *; 
}

Android 2.3.6, 4.1.1 및 4.2.1에서 테스트 및 확인되었습니다.


Android는 보안 문제를 허용하지 않습니다. 악의적 인 개발자는 사용자가 입력 한 로그인 정보를 매우 쉽게 훔칠 수 있습니다.

대신, 웹뷰에 표시되는 텍스트를 표시해야합니다. 응답 처리기를 설정하지 않는면 (다른 답변에 따라) 일부 인터넷 검색 으로이 수정 사항을 찾았습니다.

URL url = new URL("https://stackoverflow.com/questions/1381617");
URLConnection con = url.openConnection();
Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
Matcher m = p.matcher(con.getContentType());
/* If Content-Type doesn't match this pre-conception, choose default and 
 * hope for the best. */
String charset = m.matches() ? m.group(1) : "ISO-8859-1";
Reader r = new InputStreamReader(con.getInputStream(), charset);
StringBuilder buf = new StringBuilder();
while (true) {
  int ch = r.read();
  if (ch < 0)
    break;
  buf.append((char) ch);
}
String str = buf.toString();

이것은 많은 코드이며, 복사 / Paster 할 수 있고, 마지막에 strwebview에 모든 것과 동일한 html이 포함됩니다. 이 답변은 웹 페이지의 HTML을 자바의 페이지로로드하는 가장 간단한 방법 이며 Android는 작동합니다. 나는 착용 테스트하지 갑자기 부상을 입을 수 있습니다.

또한 가져 오는 URL은 하드 코딩이므로 변경해야합니다.


HTML을 먼저 얻은 다음 웹보기로 전달하지 않은 혜택이 있습니까?

private String getHtml(String url){
    HttpGet pageGet = new HttpGet(url);

    ResponseHandler<String> handler = new ResponseHandler<String>() {
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            HttpEntity entity = response.getEntity();
            String html; 

            if (entity != null) {
                html = EntityUtils.toString(entity);
                return html;
            } else {
                return null;
            }
        }
    };

    pageHTML = null;
    try {
        while (pageHTML==null){
            pageHTML = client.execute(pageGet, handler);
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return pageHTML;
}

@Override
public void customizeWebView(final ServiceCommunicableActivity activity, final WebView webview, final SearchResult mRom) {
    mRom.setFileSize(getFileSize(mRom.getURLSuffix()));
    webview.getSettings().setJavaScriptEnabled(true);
    WebViewClient anchorWebViewClient = new WebViewClient()
    {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

            //Do what you want to with the html
            String html = getHTML(url);

            if( html!=null && !url.equals(lastLoadedURL)){
                lastLoadedURL = url;
                webview.loadDataWithBaseURL(url, html, null, "utf-8", url);
            }
}

당신이 원하는 일을해야합니다. 에서 적응 이 가능한 웹보기에서 HTML 코드를 사용할 수 있습니다. 와에게 소리 https://stackoverflow.com/users/325081/aymon-fournier 그의 대답.


WebView에서 HTML을 추출하는 대신 URL에서 HTML을 추출하는 것이 좋습니다. 따라서 JSoup과 같은 보관 라이브러리를 사용하여 HTML을 탐색합니다. 다음 코드는 특정 URL에서 HTML을 가져옵니다.

public static String getHtml(String url) throws ClientProtocolException, IOException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet, localContext);
        String result = "";

        BufferedReader reader = new BufferedReader(
            new InputStreamReader(
                response.getEntity().getContent()
            )
        );

        String line = null;
        while ((line = reader.readLine()) != null){
            result += line + "\n";
        }
        return result;
    }

Sephy가 말한 것처럼 HttpClient를 사용합니다.

public String getHtml(String url) {
    HttpClient vClient = new DefaultHttpClient();
    HttpGet vGet = new HttpGet(url);
    String response = "";    

    try {
        ResponseHandler<String> vHandler = new BasicResponseHandler();
        response = vClient.execute(vGet, vHandler);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}

그것의 간단한 구현 HTML 컨텐츠의 가치를 얻으려면 HTML에 javasript 메소드가 필요합니다. 위의 코드에서와 같이 일부 변경이 필요합니다.

  public class htmldecoder extends Activity implements OnClickListener,TextWatcher
    {
    Button btsubmit; // this button in your xml file
    WebView wvbrowser;
    public void onCreate(Bundle savedInstanceState)
    {
                super.onCreate(savedInstanceState);
                    setContentView(R.layout.htmldecoder);



        btsubmit=(Button)findViewById(R.id.btsubmit);
        btsubmit.setOnClickListener(this);

        wvbrowser=(WebView)findViewById(R.id.wvbrowser);
        wvbrowser.setWebViewClient(new HelloWebViewClient());
        wvbrowser.getSettings().setJavaScriptEnabled(true);
        wvbrowser.getSettings().setPluginsEnabled(true);
        wvbrowser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        MyJavaScriptInterface myinterface=new MyJavaScriptInterface();
        wvbrowser.addJavascriptInterface(myinterface,"interface");
        webView.loadUrl("file:///android_asset/simple.html");  //use one html file for //testing put your html file in assets. Make sure that you done JavaScript methods to get //values for html content in html file . 
   }
   public void onClick(View v)
{
    if(btsubmit==v)
    {

        webView.loadUrl("javascript:showalert()");// call javascript method.  
        //wvbr
    }
}

final class MyJavaScriptInterface {



        MyJavaScriptInterface() {

        }

        public void sendValueFromHtml(String value) {
           System.out.println("Here is the value from html::"+value);
        }

    }

}

HTML의 자바 펼쳐보기

 <script type="text/javascript">
    //<![CDATA[
    var n1;
    function callme(){
    n1=document.getElementById("FacadeAL").value;
    }
    function showalert(){
     window.interface.sendValueFromHtml(n1);// this method calling the method of interface which //you attached to html file in android. // & we called this showalert javasript method on //submmit buttton click of android. 
    }
    //]]>
    </script>

& html에서 아래처럼 callme를 호출하십시오.

<input name="FacadeAL" id="FacadeAL" type="text" size="5" onblur="callme()"/>
이것이 도움이되기를 바랍니다.


디버거에 시간을 할애 할 시간이 있다면 몇 가지 Reflection 접근 방식을 시도해 보는 것이 좋습니다.

클래스 loadUrl()메서드 에서 시작 android.webkit.WebView:

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/webkit/WebView.java#WebView.loadUrl%28java.lang.String % 2Cjava.util.Map % 29

네이티브 메서드 android.webkit.BrowserFrame를 호출하는 에 도착해야합니다 nativeLoadUrl().

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/webkit/BrowserFrame.java#BrowserFrame.nativeLoadUrl%28java.lang.String % 2Cjava.util.Map % 29

네이티브 메서드의 구현은 여기에 있어야합니다.

http://gitorious.org/0xdroid/external_webkit/blobs/a538f34148bb04aa6ccfbb89dfd5fd784a4208b1/WebKit/android/jni/WebCoreFrameBridge.cpp

행운을 빕니다!


위의 주어진 방법은 웹 URL이있는 경우이지만 로컬 HTML이 있으면이 코드로 html을 가질 수도 있습니다.

AssetManager mgr = mContext.getAssets();
             try {
InputStream in = null;              
if(condition)//you have a local html saved in assets
                            {
                            in = mgr.open(mFileName,AssetManager.ACCESS_BUFFER);
                           }
                            else if(condition)//you have an url
                            {
                            URL feedURL = new URL(sURL);
                  in = feedURL.openConnection().getInputStream();}

                            // here you will get your html
                 String sHTML = streamToString(in);
                 in.close();

                 //display this html in the browser or web view              


             } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
             }
        public static String streamToString(InputStream in) throws IOException {
            if(in == null) {
                return "";
            }

            Writer writer = new StringWriter();
            char[] buffer = new char[1024];

            try {
                Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));

                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }

            } finally {

            }

            return writer.toString();
        }

참고 URL : https://stackoverflow.com/questions/8200945/how-to-get-html-content-from-a-webview

반응형