Okhttp3 简单使用(1)

Okhttp3 简单使用(1)

  • Okhttp3 是一个搞笑的HTTP 客户端
  • 支持HTTP/2,允许所有同一个主机地址的请求共享同一个socket连接;
  • 连接池减少请求延时,降低资源消耗;
  • 透明的GZIP压缩减少响应数据的大小;
  • 缓存响应内容,避免一些完全重复的请求;

基本使用

  1. 构建 OkHttpClient 对象;
  2. 构建 Request 对象
  3. 通过 OkHttpClient 和 Request 来构建 Call 对象;
  4. 调用Call 对象的方法提交请求;

使用案例代码

public class OkHttpClientUtils {

    private static int connTimeOut = 5;
    private static int readTimeOut = 20;
    private static int writeTimeOut = 10;
    public static OkHttpClient client = null;

    static {
    	// 构建 OkHttpClient 对象
        client = new OkHttpClient.Builder()
                .connectTimeout(connTimeOut, TimeUnit.SECONDS)
                .readTimeout(readTimeOut, TimeUnit.SECONDS)
                .writeTimeout(writeTimeOut, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .connectionPool(new ConnectionPool()) // 连接池
                .build();
    }

    public OkHttpClientUtils() {
    }

    public static String doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        if (!CollectionUtils.isEmpty(params)) {
            String paramStr = DexUtils.mapToString(params);
            url = url + "?" + paramStr;
        }
        // 构建 Request 对象
        Request.Builder requestBuilder = new Request.Builder();
        if (!CollectionUtils.isEmpty(headers)) {
            Iterator iterator = headers.keySet().iterator();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                requestBuilder.addHeader(key, headers.get(key));
            }
        }
        Request request = requestBuilder.get()
                .url(url)
                .build();
        // new 一个 Call 对象,并调用同步请求的方法 execute()
        Response response = client.newCall(request).execute();
        // 获取请求的响应
        String responseStr = response.body() == null ? "" : response.body().string();
        return responseStr;
    }

}
  • 以上是简单的封装了一个get 请求,同理可以封装post 请求

部分源码

  • OkHttpClient 部分,build 参数
        public Builder() {
            this.dispatcher = new Dispatcher();
            this.protocols = OkHttpClient.DEFAULT_PROTOCOLS;
            this.connectionSpecs = OkHttpClient.DEFAULT_CONNECTION_SPECS;
            this.proxySelector = ProxySelector.getDefault();
            this.cookieJar = CookieJar.NO_COOKIES;
            this.socketFactory = SocketFactory.getDefault();
            this.hostnameVerifier = OkHostnameVerifier.INSTANCE;
            this.certificatePinner = CertificatePinner.DEFAULT;
            this.proxyAuthenticator = Authenticator.NONE;
            this.authenticator = Authenticator.NONE;
            this.connectionPool = new ConnectionPool();
            this.dns = Dns.SYSTEM;
            this.followSslRedirects = true;
            this.followRedirects = true;
            this.retryOnConnectionFailure = true;
            this.connectTimeout = 10000;
            this.readTimeout = 10000;
            this.writeTimeout = 10000;
            this.pingInterval = 0;
        }
  • Request build 参数
    Request(Request.Builder builder) {
        this.url = builder.url;
        this.method = builder.method;
        this.headers = builder.headers.build();
        this.body = builder.body;
        this.tag = builder.tag != null ? builder.tag : this;
    }

PS

  • 推荐使用异步调用,讲请求加入队列中
//1,创建OKHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //2,创建一个Request
        Request request = new Request.Builder().url(Constant.URL).build();
        //3,创建一个call对象
        Call call = okHttpClient.newCall(request);
        //4,将请求添加到调度中
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) {
                if (response.isSuccessful()) {
                    try {
                        res = response.body().string();
                        ThreadPoolUtil.execute(new Runnable() {
                            @Override
                            public void run() {
                                Log.d(TAG, res);
                            }
                        });
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
发布了27 篇原创文章 · 获赞 4 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章