Android HttpClient挂起同步请求,直到我向另一台主机执行请求

时间:2012-05-28 09:47:28

标签: java android httpclient

使用DefaultHttpClient时遇到问题。

如果我同时向同一服务器(> 2)执行某些请求,它将挂起它们(不会收到任何响应)。所有下一个请求也会挂起。

这是代码。

public class ConnectionService {

    // Should be called once with application context
    public static void initWithContext(Context ctx) {
        // Creating custom multithread connection manager to handle multiple simultaneous requests
        HttpParams params = new BasicHttpParams();
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        ConnManagerParams.setMaxTotalConnections(params, 200);
        ConnPerRoute cpr = new ConnPerRoute() {
            @Override
            public int getMaxForRoute(HttpRoute httpRoute) {
                return 50;
            }
        };
        ConnManagerParams.setMaxConnectionsPerRoute(params, cpr);

        httpClient = new DefaultHttpClient(cm, params);
        httpClient.setCookieStore(new PersistentCookieStore(ctx));
    }

    static private DefaultHttpClient httpClient = null;

    private JsonExecutorInterface requestExecutorForRelativePathAndParams(String path, WebParams params) throws UnsupportedEncodingException {
        HttpPost postRequest = new HttpPost(rootUrl.toString() + path);

        if(params != null) {
            postRequest.setEntity(params.getFormEntity());
        }

        JsonExecutorProxy executor = new JsonExecutorProxy();
        executor.setRequest(postRequest);
        executor.setErrorsHandlerDelegate(this);

        return executor;
    }
}

1 个答案:

答案 0 :(得分:0)

这很可能是由于您构建正在使用的ThreadSafeClientConnManager的方式。如果你稍微改变订单,你应该会得到更好的结果。

    HttpParams params = new BasicHttpParams();
    // The params are read in the ctor of the pool constructed by
    // ThreadSafeClientConnManager, and need to be set before constructing it.
    ConnManagerParams.setMaxTotalConnections(params, 200);
    ConnPerRoute cpr = new ConnPerRoute() {
        @Override
        public int getMaxForRoute(HttpRoute httpRoute) {
            return 50;
        }
    };
    ConnManagerParams.setMaxConnectionsPerRoute(params, cpr);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);