android新手一枚,android使用httclient獲取服務(wù)器端數(shù)據(jù)失敗,但是用java工程運(yùn)行就可以成功獲取。
問題描述
各位 剛接觸android,請教個(gè)問題,android使用httpclient獲取服務(wù)器端的json數(shù)據(jù)總是失敗,但是同樣的代碼用java工程來運(yùn)行就可以獲取結(jié)果,這個(gè)是為什么?
代碼很簡短: 但是總是連接失敗
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:
網(wǎng)絡(luò)請求不要放到主線程中進(jìn)行請求,可以用Thread在主線程外進(jìn)行請求。
