各位 刚接触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
을 사용하여 메인 스레드 외부에서 요청할 수 있습니다.