Okhttp的简单使用

引入包:implementation 'com.squareup.okhttp3:okhttp:4.9.0'

//建议与单例模式一起使用,此处不做延伸

//1.创建客户端
okHttpClient = new OkHttpClient.Builder()
        //.sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager()) https协议才需要ssl
        //.hostnameVerifier(new TrustAllCerts.TrustAllHostnameVerifier())
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(500, TimeUnit.SECONDS).build();
/**
 * get异步请求
 * @param url 请求地址
 */
public void get(String url) {
    final Request request = new Request.Builder()
            .get()
            .url(url)
            .build();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(final Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                //请求成功回调内容
                String responseData = response.body().string();
            }
        }
    });
}
/**
 * post异步请求
 * @param url   请求地址
 */

public void post(String url) {
    FormBody.Builder body = new FormBody.Builder();
    body.add("key1","value1");
    body.add("参数2","参数2内容");
    Request request = new Request.Builder()
            .post(body.build())
            .url(url)
            .build();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                //请求成功回调内容
                String responseData=response.body().string();
            } 
        }
    });
}
上一篇:细节决定成败!自己动手实现OkHttp,搞懂这些直接来阿里入职


下一篇:了解一下 OkHttp