Android HttpCleint可以在2.2上工作,但不能在4上工作

Android HttpCleint可以在2.2上工作,但不能在4上工作,android,apache-httpclient-4.x,Android,Apache Httpclient 4.x,我有一个方法(如下)在我的android程序中从web服务获取数据。它在安卓2.2上运行良好。但在4.x中,它抛出一个异常,并显示消息“ErrorRequestingAPI”。不确定是哪个部分导致了代码中的异常,为什么只有在4.x中才能有人给我一些指针 public static synchronized String performHTTPRequest(HttpUriRequest request) throws ApiException, P

我有一个方法(如下)在我的android程序中从web服务获取数据。它在安卓2.2上运行良好。但在4.x中,它抛出一个异常,并显示消息“ErrorRequestingAPI”。不确定是哪个部分导致了代码中的异常,为什么只有在4.x中才能有人给我一些指针

        public static synchronized String performHTTPRequest(HttpUriRequest request)
                throws ApiException, ParseException, IOException {
            HttpClientWrapper cli=new HttpClientWrapper();
            HttpClient client;
            try {
                client=cli.getClient();
                HttpResponse response = client.execute(request);
                // Check if server response is valid
                StatusLine status = response.getStatusLine() ;

            if (status.getStatusCode() != HTTP_STATUS_OK) {
                throw new ApiException("Invalid response from server: " + status.toString());
            }
            return EntityUtils.toString(response.getEntity());
        } catch (MalformedURLException e) {
            throw new Error(e);
        }  catch (Exception cnrce) {
            throw new ApiException("Error requesting API:");
        }
    }

在4.0或以上版本中,您不能在ui线程上执行任何http请求。 您需要在asynctask中执行这些操作。 编辑:


如果您知道导致异常的详细信息,将会有所帮助。。您应该在ApiException中添加原因(基本异常),以便跟踪问题。感谢akash和Matt的回答/评论。在akash的建议之后,我尝试了一些事情,但注意到如果我在清单中设置targetSdkVersion=“8”,则该应用程序可以在版本3及更高版本中运行。(我假设在本例中不会生成NetworkOnMainThreadException)。我正在努力使它成为一个异步任务。完成后,将发布我的工作代码(使用异步任务)。谢谢你。您是否有任何示例代码可以帮助我使其成为异步任务?或者任何有帮助的文件?。再次感谢汉克斯·阿卡什。您的文档和代码示例链接非常好。