"
各位 刚接触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> 这句话我也加了
""
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();
}</code></pre>######<p>网络请求不要放到主线程中进行请求,可以用<code>Thread</code>在主线程外进行请求。</p>"
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。