发送HttpPost请求时出现SocketTimeOutException

时间:2012-05-21 15:29:12

标签: android http request apache-httpclient-4.x

我的应用程序适用于Facebook,并使用JSON参数发布请求。 请求发送约7-8分钟然后我捕获一个SocketTimeOutException。 在10分钟内,我可以再次发送请求。

以下是代码:

public static String httpTPRequest(String url, String params) {
    String response = Static.EMPTY;
    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("Content-Type", "application/json");
    HttpParams httpParams = new BasicHttpParams();
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
    HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, HTTP_TIMEOUT);

    try {
        httpPost.setEntity(new StringEntity(params, "UTF-8"));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            response = EntityUtils.toString(entity);
        }
    } catch (Exception e) {
        Debug.log(TAG, "tp server request:" + e.getMessage());
    }

    return response;
}

为什么会这样?

堆栈跟踪

SocketTimeoutException:Http::Socket stack:org.apache.harmony.luni.platform.OSNetworkSystem.connectStreamWithTimeoutSocketImpl(Native Method)
Http::Socket stack: org.apache.harmony.luni.platform.OSNetworkSystem.connectStreamWithTimeoutSocket(OSNetworkSystem.java:131)
Http::Socket stack: org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:247)
Http::Socket stack: org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:535)
Http::Socket stack: java.net.Socket.connect(Socket.java:1054)
Http::Socket stack: org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:117)
Http::Socket stack: org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:129)
Http::Socket stack: org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
Http::Socket stack: org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
Http::Socket stack: org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348)
Http::Socket stack: org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
Http::Socket stack: org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
Http::Socket stack: org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
Http::Socket stack: com.saymeow.saymeow.utils.Http.httpTPRequest(Http.java:194)
Http::Socket stack: java.lang.Thread.run(Thread.java:1096)
Http::Socket stack: com.saymeow.saymeow.requests.ApiRequest$1.run(ApiRequest.java:83)
Http::SocketTimeoutException: Socket is not connected

1 个答案:

答案 0 :(得分:-1)

如果params是JSON-String,则可能需要替换:

httpPost.setEntity(new StringEntity(params,"UTF-8"));

httpPost.setEntity(new ByteArrayEntity(params.getBytes("UTF8")));