您的位置:首页技术文章
文章详情页

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

【字号: 日期:2024-03-02 18:44:50浏览:29作者:猪猪

问题描述

各位 刚接触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 exceptionToast.makeText(getApplicationContext(), '连接失败!', Toast.LENGTH_SHORT).show();e.printStackTrace(); } httpclient.getConnectionManager().shutdown();}

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

问题解答

回答1:

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() {@Overridepublic void run() { tv.setText(content);} });} catch (Exception e) { // TODO: handle exception Toast.makeText(getApplicationContext(), '连接失败!', Toast.LENGTH_SHORT).show(); e.printStackTrace();}httpclient.getConnectionManager().shutdown(); }}.start(); }回答2:

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

标签: java