2012-09-28 126 views
0

其實這是我必須做的設置連接超時:安卓:設置連接超時的HttpPost

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); 

,但在我的應用程序使httpClient作爲MainActivities一個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); 

我只是想知道,我怎麼能在MainActivity設置params,只是使用所有其他Activitite中的httpClient,而不是在每個Activity中設置參數。

謝謝

回答

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); 
+0

我不能在聲明字段時使用像setTimeout()這樣的方法。所以我必須在活動中使用這些方法。這意味着每個活動。 –

+0

我認爲你的要求是服務器的httppost沒有得到超時excepetion。 –

+0

不需要。我必須將ConnectionTimeout參數設置爲httpClient,只有一次。並在所有其他活動中使用相同的httpClient(已在MainActivity中設置了prams)。直到現在我還沒有設置任何參數,所以我在MainActivity中創建了這個httpClient的一個靜態字段,並在所有其他活動中使用它作爲MainActivity.httpClient –

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); 
    } 


    ... 

}