首页 > 解决方案 > 使用 HttpGet 获取网页信息不起作用

问题描述

嗨,我对 android 开发非常陌生,目前正在开发我的第一个 android 应用程序项目。我想将 Web 内容加载到应用程序并将内容存储为字符串。我尝试使用 AsyncTask 进行 httpGet,但布尔 doInBackground 函数总是返回 false。我找不到原因。有人可以帮我吗?谢谢!

public class MainActivity extends Activity {
    public EditText url_text;
    public TextView textView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //url_text = (EditText) findViewById(R.id.address);
        //textView = (TextView) findViewById(R.id.tv);
        final String url = "http://www.google.com/";

        new JSONAsyncTask().execute(url);
    }

    public class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
        public String resultString = "";

        @Override
        protected Boolean doInBackground(String... params) {
            String url = params[0];
            try {
                HttpGet httpGet = new HttpGet(url);
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httpGet);

                int status = response.getStatusLine().getStatusCode();

                if (status == 200) {
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);
                    resultString = data;



                    return true;
                }
            } catch (Exception e) {

                System.out.println("Some error occured.");
            }
            return false;
        }
        @Override
        protected void onPostExecute(Boolean result){
            Log.d("TAG", resultString);
        }
    }
}

安慰: 安慰

标签: android

解决方案


推荐阅读