HttpURLConnection的总结

来源:互联网 发布:js test函数 编辑:程序博客网 时间:2024/06/07 04:45

    Android6.0(API:23)的发布,带来了许多的特性,比如近期讨论较多的运行时授权,另外,在使用6.0的API的时候,也发现HttpClient也成为了过去时。虽说在2.3后,HttpURLConnection就已经成为主流,但还是有不少人使用HttpClient,因此,这里将HttpURLConnection做个简单的介绍:

一、HttpURLConnection的API

  1. 字段
    • chunkLength:使用存储块编码流模式进行输出时的存储块长度。
    • fixedContentLength 使用固定长度流模式时的固定内容长度。
    • 其它的主要是一些状态码。(典型的为200:HTTP_OK,具体的可以参考一下这篇资料:HttpURLConnection的API)
  2. 构造方法
    • HttpURLConnection(URL u);
  3. 常用方法
    • disconnect(); 关闭连接
    • getResponseCode();获取HTTP响应消息
    • 其它方法可以根据需要选择

二、相关联的类及方法

  1. 在安卓中,使用HttpURLConnection显然要进行权限设置:

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

    其中第一条,是获取网络状态的权限,第二条是连接网络的权限
  2. URL
    HttpURLConnection的实例几乎都是由url的openConnection获得的。它表示到 URL 所引用的远程对象的连接,当然,它返回的是一个 URLConnection 对象,因此需要强制转换。
  3. 从网络总是为了获取数据的,因此,最为重要的是IO流的处理,几乎每个常用的流都有可能用到。

三、网络工具类中重用的几个方法

  1. 一般先判断网络是否可用
public static boolean isNetWorkConnection(Context context) {// 判断网络状态        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo info = manager.getActiveNetworkInfo();        if (info != null) {            // 返回网络的连接状态            return info.isConnected();        }        return false;    }

2.获得String字符串

// Android中常用来从网络获取Json字符串    public static String getJsonString(String path) {        HttpURLConnection connection = null;        StringBuffer sb = null;        try {            URL url = new URL(path);            connection = (HttpURLConnection) url.openConnection();            int code = connection.getResponseCode();            if (code == 200) {            // 得到InputStream流后,通过转换流,最后得到缓冲字符输入流                BufferedReader br = new BufferedReader(new InputStreamReader(                        connection.getInputStream(), "utf-8"));                String line;                sb = new StringBuffer();                while ((line = br.readLine()) != null) {                    sb.append(line);                }                if (br != null) {                    br.close();                }            }        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            if(fs!=null){                sb.close();            }            if (connection != null) {                connection.disconnect();            }        }        return sb.toString();    }

3.获得byte[]数组

// 一般从网络获取的是图片、音乐链接的资源使用public static byte[] getBytesResult(String path) {        HttpURLConnection connection = null;        // 因为要返回字符数组,使用ByteArrayOutputStream流        ByteArrayOutputStream baos =  new ByteArrayOutputStream();        try {            URL url = new URL(path);            connection = (HttpURLConnection) url.openConnection();            int code = connection.getResponseCode();            if (code == 200) {                InputStream is = connection.getInputStream();                int len = 0;                byte[] bytes = new byte[512];                // 流之间的转换                while ((len = is.read(bytes)) != -1) {                    baos.write(bytes, 0, len);                    baos.flush();                }                is.close();                baos.close();            }        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            if (connection != null) {                connection.disconnect();            }        }        // baos中有方法直接将流转为字符数组        return baos.toByteArray();    }
  • 一般得到的字符流需要进一步的操作,比如
    1. 得到Bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(byte[] data, int offset,int length);//offset一般为0length 可以由data.length得到。
0 0
原创粉丝点击