【问题标题】:How to add timeout to an HTTP Post如何为 HTTP Post 添加超时
【发布时间】:2012-02-22 13:48:31
【问题描述】:

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

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

【问题讨论】:

    标签: android http timeout android-internet


    【解决方案1】:

    你必须使用HttpClientHttpPost吗?您可以使用HttpURLConnection,它具有setConnectTimeout(int) 方法:

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

    【讨论】:

    • List&lt;NameValuePair&gt; nameValuePairs = new ArrayList&lt;NameValuePair&gt;(1); nameValuePairs.add(new BasicNameValuePair("ab", cd)); 的对应代码是什么,如果您可以定制代码(如链接中给出的)并使其合适,以便可以在这里使用,那将非常有帮助和高度赞赏。据我所见(在快速运行您的代码期间),这里不需要考虑任何 cookie 以及该代码中给出的许多其他内容。
    • output 字符串只是一组名称/值对,所以你会有类似:String output = "ab="+cd+"&amp;foo="+bar;
    【解决方案2】:

    你可以使用这个代码

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

    【讨论】:

      猜你喜欢
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      • 2011-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-30
      • 2011-07-16
      相关资源
      最近更新 更多