Android 网络编程(四)OkHttp3完全解析

版权声明:本文出自朋永的博客,转载必须注明出处。 https://blog.csdn.net/VNanyesheshou/article/details/77579280

OkHttp是默认情况下高效的HTTP客户端。特性:

  1. 支持HTTP/2,允许同一主机的所有请求共享套接字socket。
  2. 连接池减少请求延迟(如果HTTP / 2不可用)。
  3. 透明的GZIP压缩下载大小。
  4. 响应缓存可以避免重复请求的网络。
  5. 当网络麻烦时,OkHttp坚持不懈:它将从常见的连接问题中静默地恢复。 如果您的服务有多个IP地址,如果第一个连接失败,OkHttp将尝试替代地址。 这对于IPv4 + IPv6以及在冗余数据中心中托管的服务是必需的。 OkHttp启动与现代TLS功能(SNI,ALPN)的新连接,如果握手失败,则返回TLS 1.0。
  6. 使用OkHttp很容易 它的请求/响应API设计有流畅的构建器和不变性。 它支持同步阻塞调用和具有回调的异步调用。

Okhttp支持Android 2.3及以上版本。 对于Java,最低要求是1.7。


配置OkHttp

对于Android Studio的用户,配置gradle

compile 'com.squareup.okhttp3:okhttp:3.8.1'
compile 'com.squareup.okio:okio:1.13.0'

Eclipse的用户,可以下载最新的okhttp3、okio的jar包(下载地址:http://square.github.io/okhttp/)添加依赖就可以用了。

添加网络权限:

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

Get请求

private void get(){
    //创建OkHttpClient对象
    OkHttpClient client = new OkHttpClient();
    //创建Request
    Request request = new Request.Builder()
            .url("http://blog.csdn.net/vnanyesheshou")
            .build();
    Call mCall = client.newCall(request);
    mCall.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.i(TAG, "Thread:"+Thread.currentThread());
            String result = response.body().string();
            Log.i(TAG, result);
        }
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }
    });
}

打印信息如下:

08-29 07:24:43.833: I/OkHttpMain(1285): Thread:Thread[OkHttp http://blog.csdn.net/...,5,main]
08-29 07:24:44.233: I/OkHttpMain(1285): <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
。。。。

get请求访问我的csdn博客主页,由上述打印可知,其回调是在子线程中,不可以更新ui。


Post请求

private void post(){
    //创建OkHttpClient对象
    OkHttpClient client = new OkHttpClient();
    RequestBody body = new FormBody.Builder()
            .add("username", "520it")
            .add("pwd", "520it")
            .build();

    Request request = new Request.Builder()
            .url("http://120.25.226.186:32812/login")
            .post(body).build();
    Call mCall = client.newCall(request);
    mCall.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.i(TAG, "Thread:"+Thread.currentThread());
            String result = response.body().string();
            Log.i(TAG, result);
        }
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }
    });
}

上传单个文件

private void uploadFile(){
    OkHttpClient client = new OkHttpClient();
    File file = new File("/sdcard/test.png");
    RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);

    Request request = new Request.Builder()
               .url(url)
               .post(requestBody)
               .addHeader("Content-Type", "image/png")
               .build();

    Call mCall = client.newCall(request);
    mCall.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.i(TAG, "Thread:"+Thread.currentThread());
            String result = response.body().string();
            Log.i(TAG, result);
        }
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }
    }); 
}

下载文件

private void downloadVid(){
    OkHttpClient client = new OkHttpClient();
    String url = "http://120.25.226.186:32812/resources/videos/minion_01.mp4";
       Request request = new Request.Builder().url(url).build();
       Call mCall = client.newCall(request);
    mCall.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            InputStream inputStream = response.body().byteStream();
               FileOutputStream out = null;
               try {
                   out = new FileOutputStream(new File("/sdcard/minion_01.mp4"));
                   byte[] buffer = new byte[2048];
                   int len = 0;
                   while ((len = inputStream.read(buffer)) != -1) {
                       out.write(buffer, 0, len);
                   }
                   out.flush();
                   out.close();
               } catch (IOException e) {
                   e.printStackTrace();
              }
              Log.d(TAG, "文件下载成功 "+ Thread.currentThread());
        }
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }
    });
}

以上为OkHttp的一些简单用法。

猜你喜欢

转载自blog.csdn.net/VNanyesheshou/article/details/77579280
今日推荐