首页 > android新手一枚,android使用httclient获取服务器端数据失败,但是用java工程运行就可以成功获取。

android新手一枚,android使用httclient获取服务器端数据失败,但是用java工程运行就可以成功获取。

各位 刚接触android,请教个问题,android使用httpclient获取服务器端的json数据总是失败,但是同样的代码用java工程来运行就可以获取结果,这个是为什么?

代码很简短: 但是总是连接失败

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String content = "";
    TextView tv = (TextView) findViewById(R.id.showWiki);
    String url = "http://www.nowamagic.net/academy/android/";
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    try {
        content = httpclient.execute(httpget, responseHandler);
        Toast.makeText(getApplicationContext(), "连接成功!", Toast.LENGTH_SHORT).show();
        tv.setText(content);
    } catch (Exception e) {
        // TODO: handle exception
        Toast.makeText(getApplicationContext(), "连接失败!", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
    httpclient.getConnectionManager().shutdown();
}

<uses-permission android:name="android.permission.INTERNET"></uses-permission> 这句话我也加了


网络请求不要放到主线程中进行请求,可以用Thread在主线程外进行请求。


 private void httpRequest() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                HttpClient httpclient = new DefaultHttpClient();
                HttpGet    httpget    = new HttpGet(url);
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                try {
                    content = httpclient.execute(httpget, responseHandler);
                    Toast.makeText(getApplicationContext(), "连接成功!", Toast.LENGTH_SHORT).show();
                    //更新UI,子线程不能更新UI
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv.setText(content);
                        }
                    });
                } catch (Exception e) {
                    // TODO: handle exception
                    Toast.makeText(getApplicationContext(), "连接失败!", Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
                httpclient.getConnectionManager().shutdown();


            }
        }.start();
    }
【热门文章】
【热门文章】