OkHttp3的基本使用

OkHttp3的基本使用

八归少年 2,519 2020-01-10

Android常用框架

一、 OkHttp3

  • Okhttp是一个高效的http客户端,处理网络请求的开源项目。
特性:
  1. 能够高效的执行http,数据加载速度更快,更省流量。
  2. 支持Gzip压缩,提升速度,节省流量。
  3. 缓存响应数据,避免了重复的网络请求。
  4. 使用简单,支持同步阻塞调用和带回调的异步调用。
GitHub地址:https://github.com/square/okhttp
依赖: implementation("com.squareup.okhttp3:okhttp:4.1.0")
权限: <uses-permission android:name="android.permission.INTERNET"/>
Get请求:
	//1.创建OkhttpClient对象
        OkHttpClient client = new OkHttpClient();
	    //2.创建request对象,设置一个url地址,请求方式
        Request request = new Request.Builder()
                .url("http://www.baidu.com")
                .get()
                .build();
	    //3.创建一个call对象,参数就是request对象
        Call call = client.newCall(request);
同步Get请求:
  • 提交同步get请求会阻塞线程,避免ANR异常,需要开启一个子线程。
new Thread(){
          @Override
            public void run() {
                try {
                    Response response = call.execute();
					Log.d(TAG, response.body().toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

异步Get请求:
  //4.请求加入回调,重写回调方法
  call.enqueue(new Callback() {
	//请求失败
        @Override
        public void onFailure(Call call, IOException e) {
            Log.d(TAG, "onFailure: "+e.getMessage());
        }
	//请求成功
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.d(TAG, "onResponse: "+response.body().toString());
        }
    });

Post请求:

  • 构造request对象时,需要构造一个RequestBody对象,携带提交的数据。构造时需要指定MediaType,用于描述请求/响应的内容类型。常见类型有:

      text/html:HTML格式
      text/pain:纯文本格式
      image/jpeg:jpg图片格式
      application/json:JSON数据格式	
      application/octet-stream:二进制流数据(如常见的文件下载)
      application/x-www-form-urlencoded:form表单encType属性的默认格式,表单数据将以key/value的形式发送到服务端
      multipart/form-data:表单上传文件的格式
    
  • 上传json字符串

      OkHttpClient client = new OkHttpClient();
      //构造 RequestBody 需要指定MediaType,用于描述请求/响应 body 的内容类型
      MediaType JSON = MediaType.parse("application/json; charset=utf-8");
      String json = "{\"name\":\"zhangsan\",\"age\":\"20\"}";
      new Request.Builder()
              .url(url)
              .post(RequestBody.create(JSON, json))
              .build();
      client.newCall(request).enqueue(new Callback() {
          @Override
          public void onFailure(Call call, IOException e) {
    
          }
          @Override
          public void onResponse(Call call, Response response) throws IOException {
    
          }
      });
    
  • 上传文件

      OkHttpClient client = new OkHttpClient();
      String filePath = "C:\\Users\\yhj\\Desktop\\SoftwareFramework";
      File file = new File(filePath);
      Request request = new Request.Builder()
              .url(url)
              .post(RequestBody.create(MediaType.parse("application/octet-stream"), file))
              .build();
      client.newCall(request).enqueue(new Callback() {
          @Override
          public void onFailure(Call call, IOException e) {
    
          }
    
          @Override
          public void onResponse(Call call, Response response) throws IOException {
    
          }
      });
    
  • 提交表单文件

      OkHttpClient client = new OkHttpClient();
      RequestBody requestBody = new FormBody.Builder()
              .add("name", "value")
              .build();
      Request request = new Request.Builder()
              .url(url)
              .post(requestBody)
              .build();
      client.newCall(request).enqueue(new Callback() {
          @Override
          public void onFailure(Call call, IOException e) {
    
          }
    
          @Override
          public void onResponse(Call call, Response response) throws IOException {
    
          }
      });
    
  • 使用MultipartBody同时上传多种类型数据

      OkHttpClient client = new OkHttpClient();
      String filePath="";
      File file = new File(filePath);
      MultipartBody multipartBody = new MultipartBody.Builder()
      		//设置类型是表单
              .setType(MultipartBody.FORM)
              .addFormDataPart("name", "value")
              .addFormDataPart("name1", "value1")
              .addFormDataPart("name", file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file)).build();
      Request request = new Request.Builder()
              .url(url)
              .post(multipartBody)
              .build();
      client.newCall(request).enqueue(new Callback() {
          @Override
          public void onFailure(Call call, IOException e) {
    
          }
    
          @Override
          public void onResponse(Call call, Response response) throws IOException {
    
          }
      });
    
  • 异步下载一个图片文件

      String url="http://pic1.win4000.com/wallpaper/c/53cdd1f7c1f21.jpg";
      OkHttpClient client = new OkHttpClient();
      Request request = new Request.Builder()
              .url(url)
              .get()
              .build();
      client.newCall(request).enqueue(new Callback() {
          @Override
          public void onFailure(Call call, IOException e) {
              Log.d(TAG, "onFailure: "+e.getMessage());
          }
    
          @Override
          public void onResponse(Call call, Response response) throws IOException {
              InputStream inputStream = response.body().byteStream();
              int len=0;
              File file = new File(Environment.getExternalStorageDirectory(), "baidu.jpg");
              FileOutputStream fos = new FileOutputStream(file);
              byte[] bytes = new byte[1024];
              while ((len=inputStream.read(bytes))!=-1){
                  fos.write(bytes);
              }
              fos.flush();
              fos.close();
              inputStream.close();
          }
      });
    
  • 网络下载图片显示到ImageView中

      @Override
      public void onResponse (Call call, Response response) throws IOException {
          InputStream is = response.body().byteStream();
          //使用 BitmapFactory 的 decodeStream 将图片的输入流直接转换为 Bitmap 
          final Bitmap bitmap = BitmapFactory.decodeStream(is);
          //在主线程中操作UI
          runOnUiThread(new Runnable() {
              @Override
              public void run() {
                  //然后将Bitmap设置到 ImageView 中
                  imageView.setImageBitmap(bitmap);
              }
          });
          is.close();
      }
    
  • 设置超时时间和缓存

      OkHttpClient.Builder builder = new OkHttpClient.Builder()
              .writeTimeout(20, java.util.concurrent.TimeUnit.SECONDS)
              .connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
              .readTimeout(20,TimeUnit.SECONDS)
              .cache(new Cache(new File("pathname"),1024*1024*100));
      builder.build();
    
  • Http头部的设置和读取

    HTTP 头的数据结构是 Map<String, List<String>>类型。也就是说,对于每个 HTTP 头,可能有多个值。但是大部分 HTTP 头都只有一个值,只有少部分 HTTP 头允许多个值。至于name的取值说明,可以查看这个Http请求头大全

OkHttp的处理方式是:

  • 使用header(name,value)来设置HTTP头的唯一值,如果请求中已经存在响应的信息那么直接替换掉。

  • 使用addHeader(name,value)来补充新值,如果请求头中已经存在name的name-value,那么还会继续添加,请求头中便会存在多个name相同而value不同的“键值对”。

  • 使用header(name)读取唯一值或多个值的最后一个值

  • 使用headers(name)获取所有值

      OkHttpClient client = new OkHttpClient();
      Request request = new Request.Builder()
              .url("https://github.com")
              .header("User-Agent", "My super agent")
              .addHeader("Accept", "text/html")
              .build();
      Response response = client.newCall(request).execute();
      if (!response.isSuccessful()) {
          throw new IOException("服务器端错误: " + response);
      }
      System.out.println(response.header("Server"));
      System.out.println(response.headers("Set-Cookie"));
    

小结: OKHttp是一个处理网络请求的开源项目,Android 当前最火热网络框架,由移动支付Square公司贡献,用于替代HttpUrlConnection和Apache HttpClient(android API23 6.0里已移除HttpClient)。


Copyright: 采用 知识共享署名4.0 国际许可协议进行许可

Links: https://www.yanghujun.com/archives/okhttp3