分享

Android http请求数据 设置超时

 天海544 2014-12-01

以前一直在写http请求,设置超时也没怎么认真测试过,今天项目不怎么忙,写了一个http请求测了一下发现以前设置的超时根本没起作用,原来是在发送请求之后设置的超时时间,说着比较迷糊,还是直接上代码。

http请求代码:

  1. /** 
  2.      * http Post请求的过程 
  3.      * @param postParameters:请求服务端接口需要的数据 
  4.      * @param url:请求接口的地址 
  5.      * @return result 
  6.      */  
  7.     private static String requestPost(List<NameValuePair> postParameters,String url) {  
  8.         String result = null;  
  9.         BufferedReader in = null;  
  10.         try {  
  11.             HttpClient client = new DefaultHttpClient();  
  12.             //Represents a collection of HTTP protocol and framework parameters  
  13.             HttpParams params = null;  
  14.             params = client.getParams();  
  15.             //set timeout  
  16.             HttpConnectionParams.setConnectionTimeout(params, 5000);  
  17.             HttpConnectionParams.setSoTimeout(params, 35000);  
  18.             // url为访问地址  
  19.             HttpPost request = new HttpPost(url);  
  20.             UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(  
  21.                     postParameters,"utf-8");  
  22.             request.setEntity(formEntity);  
  23.             // 通过execute()执行httppost调用  
  24.             HttpResponse response = client.execute(request);  
  25.               
  26.             // 读取返回结果  
  27.             in = new BufferedReader(new InputStreamReader(response.getEntity()  
  28.                     .getContent()));  
  29.             StringBuffer sb = new StringBuffer("");  
  30.             String line = "";  
  31.             // 换行操作  
  32.             String NL = System.getProperty("line.separator");  
  33.             while ((line = in.readLine()) != null) {  
  34.                 sb.append(line + NL);  
  35.             }  
  36.             in.close();  
  37.             result = sb.toString();  
  38.             Log.d("返回数据", result);  
  39.         } catch (Exception e) {  
  40.             result = "NetError";  
  41.             Log.i("Error", "Exception"+e.getMessage());  
  42.         } finally {  
  43.             if (in != null) {  
  44.                 try {  
  45.                     in.close();  
  46.                 } catch (IOException e) {  
  47.                     e.printStackTrace();  
  48.                 }  
  49.             }  
  50.         }  
  51.         return result;  
  52.     }  

其实执行请求就是client.execute(request);将设置超时放在执行之前就OK了,可以控制超时随心所欲了,以前一直没注意这个问题,看了一下以前的代码,有好几处写在了execute()之后,所以感觉上是控制时间老不对,其实走的超时是默认的超时!不知道童鞋们有没有遇到同样的问题!

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多