OkHttp

OkHttp 是一款高效的 HTTP 客户端,支持 HTTP/2、连接池、透明 GZIP 等特性。本文介绍了如何添加依赖、执行 GET 和 POST 请求,包括同步和异步方式,并详细解析了 OkHttp 的拦截器机制,包括 RetryAndFollowUpInterceptor、BridgeInterceptor、CacheInterceptor、ConnectInterceptor 和 CallServerInterceptor。此外,还提到了 POST 请求中不同类型的参数传递方式以及如何处理 BootstrapMethodError 错误。
摘要由CSDN通过智能技术生成

OKhttp

简介


OKhttp是square公司出品的,它是一个高效的HTTP客户端,(Retrofit中的http通信实现也是基于OKhttp的)它有以下默认特性:

  1. HTTP/2 support allows all requests to the same host to share a socket.
  2. Connection pooling reduces request latency (if HTTP/2 isn’t available).
  3. Transparent GZIP shrinks download sizes.
  4. Response caching avoids the network completely for repeat requests.

基本使用

1.添加依赖

目前最新的okhttp的version是3.13.1

dependencies {
   

   implementation 'com.squareup.okhttp3:okhttp:3.13.1'

}

2.GET方式

(1)同步请求,关键调用okhttpClient.execute()

    private void GetOKhttp() {
   
        new Thread(new Runnable() {
   
            @Override
            public void run() {
   
                //创建OkhttpClient
                OkHttpClient okHttpClient = new OkHttpClient();
                //创建request
                Request request = new Request.Builder()
                        .url("http://www.baidu.com")
                        .build();
                //同步网络请求
                try {
   
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    //若成功返回
                    if(response.isSuccessful()){
   
                        ok_string = response.body().toString();
                        handler.obtainMessage(1).sendToTarget();
                    }
                } catch (IOException e) {
   
                    e.printStackTrace();
                }
            }
        }).start();
    }

(2)异步请求,关键调用okhttpClient.enqueue

    private void GetOKhttp() {
   
        //创建OkHttpClient实例
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建Request对象
        Request request = new Request.Builder()
                .url("http://www.baidu.com")
                .build();
        //获取Call接口
        okhttp3.Call call = okHttpClient.newCall(request);
        //异步网络请求
        call.enqueue(new okhttp3.Callback() {
   
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
   

            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
   
                Log.i("xw", "11111:" + response.isSuccessful());
            }
        });
    }

同步请求是在主线程中进行的,因此若网络请求耗时我们需要将其放在线程中去处理;而异步请求,因为回调方法中就是在子线程中实现的,因此无需另起线程。

3.POST请求

post请求也是有同步和异步的分别。我们这里就以异步情况为例:

    private void PostOKhttp() {
   
        //创建OkhttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建表单对象
        FormBody.Builder builder = new FormBody.Builder();
        //键值对输入
        builder.add("key","123123123");
        builder.add("cityname","上海");
        //创建request参数,其中需要添加pos方式
        Request request = new Request.Builder()
                .post(builder.build())
                .url("http://api.avatardata.cn/?")
                .build();
        //创建Call接口
        okhttp3.Call call = okHttpClient.newCall(request);
        //异步请求
        call.enqueue(new okhttp3.Callback() {
   
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
   
                Log.i("xw","fail!");
            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
   
                Log.i("xw","sucess!" + response.code());
                if (response.isSuccessful()){
   
                }
            }
        });
    }

post方法接收的参数是RequestBody 对象。可以传递如下几种:

FormBody对象

FormBody是RequestBody的子类。多用于传递键值对。

public final class FormBody extends RequestBody {
   
  private static final MediaType CONTENT_TYPE = MediaType.get("application/x-www-form-urlencoded");

  private final List<String> encodedNames;
  private final List<String> encodedValues;

  FormBody(List<String> encodedNames, List<String> encodedValues) {
   

JSON对象/File对象

这里关键就是在于MediaType的设置。查看源码MediaType类可以看到:

public final class MediaType {
   
  private static final String TOKEN = "([a-zA-Z0-9-!#$%&'*+.^_`{|}~]+)";
  private static final String QUOTED = "\"([^\"]*)\"";
  private static final Pattern TYPE_SUBTYPE = Pattern.compile(TOKEN + "/" + TOKEN);
  private static final Pattern PARAMETER = Pattern.
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值