久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

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

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

瀏覽:129日期: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
主站蜘蛛池模板: 新安县| 大邑县| 兴城市| 同江市| 安多县| 杨浦区| 宜州市| 白玉县| 溆浦县| 方城县| 调兵山市| 鲁甸县| 临沭县| 额济纳旗| 宜兰市| 蓬溪县| 广昌县| 西乡县| 佳木斯市| 武山县| 金山区| 阆中市| 长武县| 东莞市| 洛隆县| 饶阳县| 湖北省| 蓬溪县| 英吉沙县| 阳曲县| 铜山县| 阳信县| 麻江县| 延安市| 平远县| 南京市| 静宁县| 梅州市| 宝坻区| 珠海市| 东光县|