zoukankan      html  css  js  c++  java
  • androidHttpClient和HttpURLConnection判断网络连接

    在android项目中,经常需要用到网络,而在联网之前前,我们都要做一次网络的判断,判断当前的网络状态是否可用,然后开始请求网络。

     

    android中请求网络方式有:HttpURLConnection和HttpClient:

      第一种方式:HttpURLConnection

     

    /**

    * 使用HttpURLConnection请求Internet

    * @param context   context对象

     

     * @param isNeedProxy  是否需要代理

     

    * @param requestUrl  请求的URL

    * @param param   请求的参数

    * @return  返回一个inputstream流

    */

    public static InputStream getHttpURLConnectionInputStream(Context context,boolean isNeedProxy,String requestUrl,Map<String, String> param) {

     

    URL url;

    HttpURLConnection conn = null;

    InputStream input = null;

    try {

    url = new URL(requestUrl);

    if(isNeedProxy)   //当请求的网络为需要使用代理时

    {

    Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,new InetSocketAddress("192.168.1.23", 80));

    conn = (HttpURLConnection) url.openConnection(proxy);

    }else{

          conn = url.openConnection();

           }

    conn.setConnectTimeout(10000);    //请求超时

    conn.setRequestMethod("POST");  //请求方式

    conn.setReadTimeout(1000);   //读取超时

    conn.setDoOutput(true);

    conn.setDoInput(true);

    conn.setUseCaches(false);

           conn.setRequestProperty("Charset", "UTF-8");

           conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

    OutputStream os = conn.getOutputStream();    

    StringBuilder sb = new StringBuilder();

    Iterator<String> it = param.keySet().iterator();

    while (it.hasNext()) {

    String key = it.next();

    String value = param.get(key);

    sb.append(key).append("=").append(value).append("&");

    }

    String p = sb.toString().substring(0, sb.length()-1);

           os.write(p.getBytes("utf-8"));

           os.close();

           if(conn!=null)

           {

           input = conn.getInputStream();

           }

     

    } catch (Exception e) {

    e.printStackTrace();

    }

    return input;

    }

    上面这种方式就是HttpURLConnection ,这种方式在android开发中也是比较常用的。

    第二种方式:HttpClient

     

    /**

     * 使用HttpURLConnection请求Internet

     * @param context   context对象

     * @param isNeedProxy  是否需要代理

     * @param requestUrl  请求的URL

     * @param param   请求的参数

     * @return  返回一个inputstream流

     */

    public static InputStream getHttpClientInputStream(Context context,boolean isNeedProxy,String requestUrl, Map<String, String> param)throws Exception {

    HttpClient client = new DefaultHttpClient();

    if(isNeedProxy)    //当请求的网络为需要使用代理时

    HttpHost proxy = new HttpHost("192.168.1.23", 80);

    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,

    proxy);

    }

    HttpPost hp = new HttpPost(requestUrl);

    hp.setHeader("Charset", "UTF-8");

    hp.setHeader("Content-Type", "application/x-www-form-urlencoded");

    List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();

     

    Iterator<String> it = param.keySet().iterator();

    while (it.hasNext()) {

    String key = it.next();

    list.add(new BasicNameValuePair(key, param.get(key)));

    }

    hp.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));

    HttpResponse response = null;

    response = client.execute(hp);

    return response.getEntity().getContent();

    }

    注意:这里的response.getEntity().getContent()只能使用一次,如果调用了多次会抛异常:java.lang.IllegalStateException: Content has been consumed

    HttpClient通常比HttpURLConnection要好用些。

  • 相关阅读:
    python实现布隆过滤器及原理解析
    gin框架源码解析
    阿里云docker操作问题记录
    Qt编写数据可视化大屏界面电子看板系统
    CSS3-3D制作案例分析实战
    前端可视化项目流程,涉及three.js(webGL),3DMax技术,持续更新
    前端可视化项目流程,涉及three.js(webGL),3DMax技术,持续更新
    jquery拖拽排序,针对后台列表table进行拖拽排序(Echart不刷新页面,多语言切换下的地图数据重新加载,api请求数据加载
    Java 设置Excel条件格式(高亮条件值、应用单元格值/公式/数据条等类型)C# 创建Excel气泡图
    Java 如何在PPT中设置形状组合、取消组合、编辑组合形状
  • 原文地址:https://www.cnblogs.com/fx2008/p/3133221.html
Copyright © 2011-2022 走看看