Getting an exception while using HttpResponse response = client.execute(request);
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){
}
w开发者_如何学Gohen I execute, program enter the catch block!
please help me !!! thx in advance!
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.
The answer of dell116 are right.
I had the same problem on ICS and solve it asynchronously with this code:
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);
}
};
Regards! :)
精彩评论