Httpclient执行总是在第二次执行后失败(IOExpception,套接字超时)

时间:2015-06-10 16:07:24

标签: android sockets

有人看到原因吗?似乎服务器没有任何问题,因为我可以一直发送curl请求。我第二次尝试查询服务器后才得到套接字超时异常。如果我重新启动应用程序,它将首次启动,然后停止。

 String params = String.format(params);
    HttpParams httpParameters = new BasicHttpParams();
    DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
    int connectionTimeout = 1000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout);
    int socketTimeout = 1000;
    HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout);

    HttpPost httppost = new HttpPost("http://example.com");
    httppost.setHeader("Content-type", "application/json");
    httppost.addHeader("Cookie", cookie);;

    try {
        httppost.setEntity(new StringEntity(parameters, "utf-8"));
    } catch (UnsupportedEncodingException e) {
        return ("ERROR_UnsupportedEncodingException");
    }
    InputStream inputStream = null;
    String stream = null;

    try {
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        inputStream = entity.getContent();

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
        StringBuilder a= new StringBuilder();

        String line = null;

        while ((line = reader.readLine()) != null) {
            a.append(line + "\n");
        }

        stream = a.toString();

        if (inputStream != null) {
            inputStream.close();
        }
    } catch (UnsupportedEncodingException e) {
        return ("ERROR_UnsupportedEncodingException");
    } catch (ClientProtocolException e) {
        return ("ERROR_ClientProtocolException");
    } catch (IOException e) {
        return ("ERROR_IOException");
    }

0 个答案:

没有答案