【Android开发--新手必看篇】依赖框架OkHttp3的使用

Android笔记

​ ——Okhttp
若对该知识点有更多想了解的,欢迎私信博主~~

依赖框架:Okhttp3
一:优势及作用
  1. 支持HTTP/2,允许所有同一个主机地址的请求共享同一个socket连接
  2. 连接池减少请求延时
  3. 透明的GZIP压缩减少响应数据的大小
  4. 缓存响应内容,避免一些完全重复的请求
二:Okhttp3的配置
  1. 在app的 build.gradle中dependencies中添加

    implementation 'com.squareup.okhttp3:okhttp:3.12.1'
    debugImplementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
    
三:使用
import android.os.Handler;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpTool {
    public static void myPost(final String url, final String json, final NetBack netBack) {
        final Handler handler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //构造RequestBody:携带要填充的数据 以及 数据格式
                    RequestBody body = RequestBody.create(
                            MediaType.parse("application/json;charset=utf-8"), json
                    );
                    //构造Request请求对象:url()--请求的地址,post()--post方法,默认get方法
                    Request request = new Request.Builder()
                            .url(url)
                            .post(body)
                            .build();
                    //构造OkHttpClient发起请求:newCall()--发起请求
                    //并构造Response接收返回结果:execute()--执行接收
                    Response response = new OkHttpClient()
                            .newCall(request)
                            .execute();
                    //获取Response返回的内容
                    final String rjson = response.body().string();
                    //返回结果
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            netBack.OnSuccess(rjson);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
public interface NetBack {
    void OnSuccess(String rjson);
}
参考资料:
  1. https://www.jianshu.com/p/da4a806e599b
  2. https://github.com/square/okhttp
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值