2

我的应用程序与 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
4

1 回答 1

-1

如果 params 是 JSON 字符串,您可能需要替换:

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

httpPost.setEntity(new ByteArrayEntity(params.getBytes("UTF8")));
于 2012-05-21T16:07:22.683 回答