Android: get HTML from web page as String with HttpClient not working

前端 未结 1 1357
别那么骄傲
别那么骄傲 2021-01-07 07:37

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

相关标签:
1条回答
  • 2021-01-07 07:50

    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);
    
                }
            }
    }
    
    0 讨论(0)
提交回复
热议问题