2012-01-30 29 views
0

爲什麼代碼不適合我,即使連接過時,(長時間沒有服務器響應,代碼沒有拋出任何異常!如何給HTTP發帖添加超時

try{ 

    HttpParams httpParameters = new BasicHttpParams(); 
    HttpConnectionParams.setConnectionTimeout(httpParameters, 5000); 
    HttpConnectionParams.setSoTimeout(httpParameters, 3000); 
    HttpClient client = new DefaultHttpClient(httpParameters);    
    HttpPost post = new HttpPost("url"); 
    post.setParams(httpParameters); 
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
    nameValuePairs.add(new BasicNameValuePair("ab ", cd)); 
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));   
    HttpResponse response = client.execute(post);   
    BufferedReader rd = new BufferedReader(new 

    InputStreamReader(response.getEntity().getContent()));    
    while ((line = rd.readLine()) != null) 
    { 

    } 
    } 
    catch(java.net.SocketTimeoutException e4) 
    { 
     Toast.makeText(xyz.this, "Your connection is stale", 10000).show(); 
    } 
    catch (IOException e2) 
    { 
    Log.d("G22", "Entered Exception");  
    } 
    catch (Exception e2) 
    { 
     Toast.makeText(xyz.this, "Your connection is stale..", 10000).show(); 
     e2.printStackTrace(); 
     Log.d("G22", "Entered Exception");  
    } 

回答

1

你有使用HttpClientHttpPost你可以使用一個HttpURLConnection,它具有setConnectTimeout(int)方法:

見我的回答here使用HttpsURLConnection的POST操作的例子

+0

什麼是對應代碼''列表<的NameValuePair> namevaluepairs中=新的ArrayList <的NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair(「ab」,cd));''如果您可以定製代碼(如鏈接中給出的)並使其適用於此,這將非常有用並且非常讚賞。就我所見(在快速瀏覽代碼的過程中),這裏不需要任何cookie代碼以及代碼中給出的許多其他內容。 – 2012-01-30 20:34:50

+1

'output'字符串只是一組名稱/值對,所以你應該有這樣的內容:'String output =「ab =」+ cd +「&foo =」+ bar;' – 2012-01-30 20:40:17

0

U可以使用此代碼

HttpTransportSE MyandroidHttpTransport = new HttpTransportSE("http://www.webservicex.net/ConvertWeight.asmx",50000); 
    //50000 is the timeout for this connection