我想在數據庫中放入一個entry。用的下面的代碼:
String url = String.format("http://xxxxxxx/xxx/index.php?home=yes&pid=%s", pid);
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
Log.e("abc", response);
return response;
} catch (ClientProtocolException es)
{
Log.e("x" , es.getMessage());
return "";
} catch (IOException e)
{
Log.e("aasx" , e.getMessage());
return "";
}
這段代碼能正常運行,現在當有網絡連接的時候,代碼就會困在httpclient.execute(httppost, responseHandler);
大約倆分鐘。
有什麼方法可以實現檢查幾秒鐘後,如果沒有反應的就會就catch the exceptions
?
HttpParams params =new BasicHttpParams();
// 設置一些基本參數
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params,CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
/* 從連接池中取連接的超時時間 */
ConnManagerParams.setTimeout(params, 1000);
/* 連接超時 */
HttpConnectionParams.setConnectionTimeout(params, 2000);
/* 請求超時 */
HttpConnectionParams.setSoTimeout(params, 4000);
// 設置我們的HttpClient支持HTTP和HTTPS兩種模式
SchemeRegistry schReg =new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
// 使用線程安全的連接管理來創建HttpClient
ClientConnectionManager conMgr =new ThreadSafeClientConnManager(params, schReg);
HttpClient httpclient=new DefaultHttpClient(conMgr, params);