安卓:用HttpClient从网页上获取HTML为字符串,不工作[英] Android: get HTML from web page as String with HttpClient not working

本文是小编为大家收集整理的关于安卓:用HttpClient从网页上获取HTML为字符串,不工作的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在编程使用HTTPCLIENT连接到网页的应用程序(目的是能够将网页的某些HTML复制到字符串中).我尝试通过使用HTTPCLIENT连接来实现这一目标.这是我使用的代码:

public void getText() {
    final TextView contentView = (TextView) findViewById(R.id.textview);
   String url = "http://www.anandtech.com";
    /* An instance of this class will be registered as a JavaScript interface */ 
HttpClient client = new DefaultHttpClient();

HttpGet get = new HttpGet(url);
ResponseHandler<String> handler = new BasicResponseHandler();
try {
    String response = client.execute(get, handler);
    contentView.setText(response);
} catch (Exception e) {
    // TODO Auto-generated catch block
    contentView.setText(e.getMessage());
}

}

我通过删除该块的每个语句,然后测试错误是否仍然发生,发现错误源自client.ecute(get,handler).我有权在AndroidManifest.xml上使用Internet,并且我知道该应用程序上的Internet可以正常工作,因为WebView可以加载正常.我该如何做这项工作?

另外,我尝试通过将JavaScript注入WebView URL,并带有以下代码:

myjavascriptInterface.class 类myjavascript Interface { 私有文本视图contentview;

        public MyJavaScriptInterface(TextView aContentView)
        {
            contentView = aContentView;
        }
    }

mainActivity.java @suppresswarnings("未使用")

        public void processContent(String aContent) 
        { 
            final String content = aContent;
            contentView.post(new Runnable() 
            {    
                public void run() 
                {          
                    contentView.setText(content);        
                }     
            });
        } 
    } 

    webView.getSettings().setJavaScriptEnabled(true); 
    webView.addJavascriptInterface(new MyJavaScriptInterface(contentView),"INTERFACE"); 
    webView.setWebViewClient(new WebViewClient() { 
        @Override 
        public void onPageFinished(WebView view, String url) {
        webView.loadUrl("javascript:window.INTERFACE.processContent(
        document.getElementsByTagName('p')[0].innerHTML);");
        } 
    }); 

    webView.loadUrl("http://tabshowdown.blogspot.com");

在活动的空白方法中定义了类和processContent()方法.在这种情况下,问题是JavaScript没有启动ProcessContent()方法,因为a.如果我尝试初始化任何其他JavaScript命令,例如document.write(),WebView反应,因此JavaScript不是问题.如果我尝试从脚本上的其他任何地方启动myjavascriptInterface和processContent()方法,则可以正常工作.因此,在我看来,JavaScript在启动该方法时遇到了麻烦(即使其他用户报告了此方法工作).

有人可以帮助我获得这些方法的工作吗? 预先感谢

推荐答案

这应该有效:

public class MainActivity extends Activity{
    private TextView contentView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(your layout);
        contentView = (TextView) findViewById(R.id.textview);
        DownloadTask task = new DownloadTask();
        task.execute(url);
    }
    private class DownloadTask extends AsyncTask<String, Void, String>{

            @Override
            protected String doInBackground(String... urls) {
                HttpResponse response = null;
                HttpGet httpGet = null;
                HttpClient mHttpClient = null;
                String s = "";

                try {
                    if(mHttpClient == null){
                        mHttpClient = new DefaultHttpClient();
                    }


                    httpGet = new HttpGet(urls[0]);


                    response = mHttpClient.execute(httpGet);
                    s = EntityUtils.toString(response.getEntity(), "UTF-8");


                } catch (IOException e) {
                    e.printStackTrace();
                } 
                return s;
            }

            @Override
            protected void onPostExecute(String result){
                contentView.setText(result);

            }
        }
}

本文地址:https://www.itbaoku.cn/post/102574.html

问题描述

I am programming an app that uses HttpClient to connect to a web page (the aim is to be able to copy some of the HTML of a webpage into a String). I tried accomplishing this by using an HttpClient connection. This is the code I used:

public void getText() {
    final TextView contentView = (TextView) findViewById(R.id.textview);
   String url = "http://www.anandtech.com";
    /* An instance of this class will be registered as a JavaScript interface */ 
HttpClient client = new DefaultHttpClient();

HttpGet get = new HttpGet(url);
ResponseHandler<String> handler = new BasicResponseHandler();
try {
    String response = client.execute(get, handler);
    contentView.setText(response);
} catch (Exception e) {
    // TODO Auto-generated catch block
    contentView.setText(e.getMessage());
}

}

I found the source of the error by removing each statement of this block and then testing if the error still occurs and found that the error originated from the client.execute(get, handler). I have permission to use internet on AndroidManifest.xml, and I know the internet works anyway on the app because a WebView can load just fine. How can I make this work?

Also, I tried to get the String by injecting javascript into a webview url, with the following code:

MyJavaScriptInterface.class class MyJavaScriptInterface { private TextView contentView;

        public MyJavaScriptInterface(TextView aContentView)
        {
            contentView = aContentView;
        }
    }

MainActivity.java @SuppressWarnings("unused")

        public void processContent(String aContent) 
        { 
            final String content = aContent;
            contentView.post(new Runnable() 
            {    
                public void run() 
                {          
                    contentView.setText(content);        
                }     
            });
        } 
    } 

    webView.getSettings().setJavaScriptEnabled(true); 
    webView.addJavascriptInterface(new MyJavaScriptInterface(contentView),"INTERFACE"); 
    webView.setWebViewClient(new WebViewClient() { 
        @Override 
        public void onPageFinished(WebView view, String url) {
        webView.loadUrl("javascript:window.INTERFACE.processContent(
        document.getElementsByTagName('p')[0].innerHTML);");
        } 
    }); 

    webView.loadUrl("http://tabshowdown.blogspot.com");

Both the class and the processContent() method were defined in the Activity's void onCreate method, FIY. In this case the problem is the javascript isn't initiating the processContent() method, since a. If I try to initialize any other javascript command, e.g. document.write(), the webview reacts, so javascript isn't the problem. If I try to initiate the MyJavaScriptInterface and the processContent() method from anywhere else on the script, it works just fine. So it appears to me as if the javascript is having trouble initiating the method (even though other users reported this method to work).

Can someone help me get either of these methods to work? Thanks in advance

推荐答案

This should work:

public class MainActivity extends Activity{
    private TextView contentView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(your layout);
        contentView = (TextView) findViewById(R.id.textview);
        DownloadTask task = new DownloadTask();
        task.execute(url);
    }
    private class DownloadTask extends AsyncTask<String, Void, String>{

            @Override
            protected String doInBackground(String... urls) {
                HttpResponse response = null;
                HttpGet httpGet = null;
                HttpClient mHttpClient = null;
                String s = "";

                try {
                    if(mHttpClient == null){
                        mHttpClient = new DefaultHttpClient();
                    }


                    httpGet = new HttpGet(urls[0]);


                    response = mHttpClient.execute(httpGet);
                    s = EntityUtils.toString(response.getEntity(), "UTF-8");


                } catch (IOException e) {
                    e.printStackTrace();
                } 
                return s;
            }

            @Override
            protected void onPostExecute(String result){
                contentView.setText(result);

            }
        }
}