【问题标题】:Error in HttpResponse/httpClient.execute [closed]HttpResponse/httpClient.execute 中的错误 [关闭]
【发布时间】:2013-11-21 12:21:59
【问题描述】:

我是 Android 新手,也是 Stackoverflow 新手!

我只是在创建虚拟应用程序来学习 http 连接。 在编译时我在这一行遇到了一个错误

HttpResponse getbackdata= http_client.execute(url_data);

我什至在 stackoverflow 中进行了搜索,但大多数人都建议使用异常处理来捕获 UnknownHostException。我这样做了。我不知道我在哪里弄乱了代码。 这可能是一个小错误,因为我是初学者,我会从中学习。 提前致谢。

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);         

        try {
            HttpClient http_client=new DefaultHttpClient();
            URI url=new URI("http://www.mysite.com");
            HttpGet url_data=new HttpGet(url);

            HttpResponse getbackdata= http_client.execute(url_data);

            InputStreamReader in =new InputStreamReader(getbackdata.getEntity().getContent());
            BufferedReader br = new BufferedReader(in);

            StringBuffer sb=new StringBuffer("");
            String info="";
            String nl=System.getProperty("line.separator");

            while((info=br.readLine())!=null){
                sb.append(info.toString()+nl);
            }
            br.close();
            TextView output=(TextView) findViewById(R.id.display_output);
            output.setText(sb.toString());
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            Log.d("ARR_ERROR","UnknownHostException : "+e);
        }
         catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            Log.d("ARR_ERROR","ClientProtocolException : "+e);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.d("ARR_ERROR","IOException : "+e);
        }
         catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        Log.d("ARR_ERROR","URISyntaxException : "+e);
    }


}

【问题讨论】:

  • 使用异步类。发布 logcat。
  • 我想知道为什么该死的人会否决我的问题!

标签: java android httpconnection


【解决方案1】:

注意:您无法在主 UI 线程上更新数据。

为此,您必须使用 AsyncTaskThread with Handler 并使用 runOnUiThread() 方法更新您的数据。

你也可以这样做:

http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html

【讨论】:

    【解决方案2】:

    让我猜猜,你收到的是NetworkOnMainThreadException,对吧?为您的网络任务使用AsyncTask。不要在 UI 线程上执行它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 2012-08-23
      相关资源
      最近更新 更多