0

我在 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");
4

1 回答 1

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();
            }
        }
    }
}
于 2013-01-02T08:25:39.523 回答