0

实际上这是我必须做的设置连接超时:

HttpGet httpPost = new HttpGet("www.xxxx.com/method");
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used. 
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT) 
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);

但是在我的应用程序中,我在 MainActivities中将其httpClient作为 a并在所有其他活动中使用它。Static field只是为了开会。

所以,我应该在所有活动中都有这个代码:

HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used. 
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT) 
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

接着

MainActivity.httpClient.setParams(httpParameters);

我只想知道,我如何在所有其他 ActivityparamsMainActivity设置并只使用 httpClient,而不是在每个 Activity 中设置参数。

谢谢你

4

2 回答 2

3

在主活动类中使用静态代码块来设置参数。

public class MainActivity extends Activity {

    static final DefaultHttpClient httpClient;

    static {    
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);
        httpClient = new DefaultHttpClient(httpParameters);
    }


   ...

}
于 2013-07-31T21:57:04.263 回答
2

尝试这个:

创建变量,如:

    private static final long CONN_MGR_TIMEOUT = 10000;
    private static final int CONN_TIMEOUT = 50000;
    private static final int SO_TIMEOUT = 50000;

并将此代码与 httppost 一起使用:

    ConnManagerParams.setTimeout(params, CONN_MGR_TIMEOUT);
    HttpConnectionParams.setConnectionTimeout(params, CONN_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
于 2012-09-28T06:24:17.510 回答