如何向HTTP Post添加超时

时间:2012-01-30 19:17:24

标签: android http timeout android-internet

为什么代码对我不起作用,即使连接是陈旧的,(服务器很长时间没有响应,代码也没有抛出任何异常!

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

2 个答案:

答案 0 :(得分:1)

您是否必须使用HttpClientHttpPost?您可以使用HttpURLConnection,其中包含setConnectTimeout(int)方法:

有关使用HttpsURLConnection进行POST操作的示例,请参阅我的回答here

答案 1 :(得分:0)

你可以使用这段代码

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