我在Android中有一种调用Web服务的方法,如下所述。
现在,当我的类调用此方法时,我无法看到任何异常,只能在System.out.println("entered into call service method 2");
日志之前。我可以在logcat看到
状态response = httpclient.execute(httppost);
不起作用,System.out.println("entered into call service method 3");
没有在logcat上显示任何异常。
知道为什么会这样吗?如何解决?
public void callService() throws Exception {
System.out.println("entered into call service method");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:81/a.php");
HttpResponse response;
System.out.println("entered into call service method 1");
try{
System.out.println("entered into call service method 2");
**response = httpclient.execute(httppost);**
System.out.println("entered into call service method 3");
答案 0 :(得分:1)
您是否在单独的Thread / AsyncTask中调用此函数?如果您的应用中经常使用请求,我还建议您考虑使用服务。
这是一个适用于我的POST方法,但不要忘记以某种方式异步调用它:
public void executePost(String url, List<NameValuePair> postParams) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStream is = null;
try {
httppost.setEntity(new UrlEncodedFormEntity(postParams));
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
if (entity != null) {
is = entity.getContent();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int inChar;
while ((inChar = is.read()) != -1) {
bos.write(inChar);
}
String resp = bos.toString();
// report back the resp e.g. via LocalBroadcast message
} else {
// report back e.g. via LocalBroadcast message
}
}
else {
// report back e.g. via LocalBroadcast message
}
} catch (Exception e) {
// report back the exception e.g. via LocalBroadcast message
// exception message: e.getMessage()
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}