Heim > Fragen und Antworten > Hauptteil
各位 刚接触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> 这句话我也加了
大家讲道理2017-04-17 17:26:51
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() {
@Override
public void run() {
tv.setText(content);
}
});
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), "连接失败!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
}
}.start();
}