我正在尝试从服务器请求响应,但是当我使用“HttpResponse response = client.execute(request);”时,程序进入异常情况。
这是我的代码:
从服务器获取响应的功能
public String executeHttpGet(String username,String password)抛出异常{
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块!
请帮帮我!!! 提前thx!
答案 0 :(得分:2)
如果您要针对任何版本的Android> = Honeycomb构建,则无法在主线程上进行网络调用。尝试将其放入异步任务中,看看它是否有效。
答案 1 :(得分:0)
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);
}
};
问候! :)