我正在尝试请求服务器的响应,但是当我使用"HttpResponse response = client.execute(request);"时,程序进入异常情况。
下面是我的代码: 从服务器获取响应的函数公共字符串executeHttpGet(字符串用户名,字符串密码)抛出异常{
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://emapzoom.com/setting/device_login"+ "?device_id=" +password+ "&login_name="+ username));
HttpResponse response = client.execute(request);
in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
System.out.println(page);
return page;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
活动使用的代码
try{
test=executeHttpGet(name,pass);
}catch(Exception e){
}
执行时,程序进入catch块!
请帮帮我!!提前感谢!
如果你是基于Android>= Honeycomb的任何版本进行构建,你都不能在主线程上进行网络调用。
dell116的答案是正确的。
我在ICS上遇到了同样的问题,并使用以下代码异步解决:
private void getResponseThread(final String url) {
new Thread(new Runnable() {
public void run() {
String cadHTTP = getResponse(url);
Message msg = new Message();
msg.obj = cadHTTP;
handlerHTTP.sendMessage(msg);
}
}).start();
}
private String getResponse(String url) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet del = new HttpGet(url);
del.setHeader("content-type", "application/json");
String respStr;
try {
HttpResponse resp = httpClient.execute(del);
respStr = EntityUtils.toString(resp.getEntity());
} catch(Exception ex) {
Log.e("RestService","Error!", ex);
respStr = "";
}
Log.e("getResponse",respStr);
return respStr;
}
private Handler handlerHTTP = new Handler() {
@Override
public void handleMessage(Message msg) {
String res = (String) msg.obj;
//CONTINUE HERE
nexTask(res);
}
};
问候!:)