HttpURLConnection的使用

2018-09-07  本文已影响0人  我就是非主流

最近在做项目时遇到一个需求,就是上传文件时展示上传进度,但是项目所里用的网络框架是Retrofit。很不凑巧,这货能上传文件,但无法获取上传进度。这时面前摆着两种选择,第一是扩展现有的Retrofit框架,第二是采用别的网络框架。如果采用第一种方案的话需要扒Retrofit源码,在其源码基础上进行扩展,但这样做的话很费时费力,一切未知。所以我就决定采取第二种方案,用最原始的网络框架进行编写,即不需要额外再依赖别的开源框架。
AnroidSDK本身自带两种网络框架HttpClient和HttpURLConnection,但Google在API23之后放弃了HttpClient的支持推荐使用HttpURLConnection,所以顺势而为我也决定采用HttpURLConnection,就这样开始了我的HttpURLConnection钻研之路。

1.基本的网络请求
HttpURLConnection urlConnection = null;
        try {
            URL url = new URL("http://www.android.com/");
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        //    读取响应的流
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(urlConnection != null){
                urlConnection.disconnect();
            }
        }
2.输出到服务端

1.建立链接并setDoOutput()设置为true,表明是输出模式,默认值是false;
2.如果预先知道输出流的长度则调用setFixedLengthStreamingMode(),若不知道时调用setChunkedStreamingMode()。否则HttpURLConnection将被迫在传输完整的请求体之前在内存中缓冲,从而浪费(并且可能耗尽)堆和增加延迟。

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     urlConnection.setDoOutput(true);
     urlConnection.setChunkedStreamingMode(0);

     OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
     writeStream(out);

     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
   } finally {
     urlConnection.disconnect();
   }
上一篇 下一篇

猜你喜欢

热点阅读