您的位置:首頁技術文章
文章詳情頁

android新手一枚,android使用httclient獲取服務器端數據失敗,但是用java工程運行就可以成功獲取。

瀏覽:102日期:2024-03-02 18:44:50

問題描述

各位 剛接觸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
国产综合久久一区二区三区