• 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要好用些。

  • 相关阅读:
    PMP考试终于结束了。。。
    干系人的管理
    设计业务时要兼顾实现方案的可行性和方案的可操作性
    办公室政治的问题
    SQL Server 2005/2008遍历所有表更新统计信息
    C1控件的破解步骤
    [七、项目实战]22开始制作一份网站访问量的统计页面
    [七、项目实战]17完成自定义弹出窗口的制作
    [七、项目实战]18给页面里的内容添加动画效果
    [七、项目实战]16利息支付方式设置界面的制作
  • 原文地址:https://www.cnblogs.com/fx2008/p/3133221.html
Copyright © 2020-2023  润新知