使用 HttpResponse 时出现异常 response = client.execute(request);
我试图从服务器请求响应,但是当我使用“HttpResponse response = client.execute(request);”时,程序进入异常情况。
这是我的代码:
用于从服务器获取响应的函数
public StringexecuteHttpGet(String username, String password) throws Exception {
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 块!
请帮我 !!! 提前谢谢!
I'm trying to request the response from server, but when I use "HttpResponse response = client.execute(request);", program enters the exception case.
Here is my code:
function for getting response from server
public String executeHttpGet(String username, String password) throws Exception {
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();
}
}
}
}
code used in activity
try{
test=executeHttpGet(name,pass);
}catch(Exception e){
}
when I execute, program enter the catch block!
please help me !!!
thx in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您正在针对任何版本的 Android >= Honeycomb 进行构建,则无法在主线程上进行网络调用。尝试将其放入异步任务中,看看它是否有效。
If you're building against any version of Android >= Honeycomb you cannot make network calls on the main thread. Try putting this in an Async Task and see if it works.
dell116的回答是正确的。
我在 ICS 上遇到了同样的问题,并使用以下代码异步解决了它:
问候! :)
The answer of dell116 are right.
I had the same problem on ICS and solve it asynchronously with this code:
Regards! :)