安卓开发,HttpResponse httpResponse = httpClient.execute(new HttpGet(url));语句无法执行的问题。

急需解决。写安卓程序,功能是从网上读取一个文本文件并打印出来,但是执行到HttpResponse httpResponse = httpClient.execute(new HttpGet(url));就停住了(由打印调试可得到这个结论),请求热心网友帮助!代码如下:
(由于字数限制,导入的包名没有列出,末尾加/////////的为调试语句)
public class MainActivity extends Activity {
private Button geocoding = null;

private Button reverseGeocoding = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
geocoding = (Button)findViewById(R.id.geocoding);
geocoding.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {

new Thread(){
public void run(){
Log.d("yinan", "run");/////////
String url = "http://maps.google.com/maps/api/geocode/json?address=SFO&sensor=false";
String responseData = "" ;
Log.d("yinan", "url");/////////
HttpClient httpClient = new DefaultHttpClient();
Log.d("yinan", "DefaultHttpClient");/////////
try {
Log.d("yinan", "#############");/////////
HttpResponse httpResponse = httpClient.execute(new HttpGet(url));//发送一个GET请求
Log.d("yinan", "httpResponse");/////////
HttpEntity entity = httpResponse.getEntity();
Log.d("yinan", "Entity!!!");/////////
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
String str;
Log.d("yinan", "OnClickListener");/////////
while((str = br.readLine()) != null){
Log.d("yinan", str);
}

} catch (ClientProtocolException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
}

}.start();

}

});
}
}

这句话是一个阻塞语句,会等到执行完成了才会继续向下进行,如果访问的URL不能访问,就会停留很久,然后抛出超时异常。

你的代码有问题的,在onclick里面不能直接访问网络,因为这个是在主线程里(UI线程),你要新开一个线程才能访问网络
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-12-03
没申请权限?
在Manifest.xml的根节点下加入
<uses-permission android:name="android.permission.INTERNET"/>追问

已经加了。

第2个回答  2014-12-03
看logcat 打印的信息啊,再定位自己的错误