Android OkHttp

目录

1.build.gradle

2.基本使用

3.POST请求

4.Builder构建者

1.build.gradle
java 复制代码
implementation("com.squareup.okhttp3:okhttp:4.12.0")
2.基本使用

GET同步请求

java 复制代码
public void getSync(View view) {
        new Thread(){
            @Override
            public void run() {
                Request request = new Request.Builder().url("https://httpbin.org/get?a=1&b=2").build();
                //准备好请求的call对象
                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    Log.i("TAG", "getSync: "+response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

GET异步请求

java 复制代码
public void getAsync(View view) {
        Request request = new Request.Builder().url("https://httpbin.org/get?a=1&b=2").build();
        //准备好请求的call对象
        Call call = okHttpClient.newCall(request);
        //异步请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.i("TAG", "getAsync onFailure",e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()){
                    Log.i("TAG", "getAsync onResponse: "+response.body().string());
                }
            }
        });
    }

POST同步请求

java 复制代码
public void postSync(View view) {
        new Thread(){
            @Override
            public void run() {
                FormBody formBody = new FormBody.Builder()
                        .add("a","404").build();
                Request request = new Request.Builder().url("https://httpbin.org/post")
                        .post(formBody).build();   //Request.Builder对象默认get请求
                //准备好请求的call对象
                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    Log.i("TAG", "postSync: "+response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

POST异步请求

java 复制代码
public void postAsync(View view) {
        FormBody formBody = new FormBody.Builder()
                .add("a","404").build();
        Request request = new Request.Builder().url("https://httpbin.org/post")
                .post(formBody).build();
        //准备好请求的call对象
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.i("TAG", "postAsync onFailure",e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.i("TAG", "postAsync: "+response.body().string());
            }
        });
}
3.POST请求

协议规定 POST 提交的数据必须放在请求体中,但协议并没有规定数据必须使用什么编码方式 。常用的数据编码方式有: https://www.runoob.com/http/http-content-type.html
Content-Type:application/x-www-form-urlencoded
数据被编码为名称/值对,默认类型;
• Content-Type:multipart/form-data
数据被编码为一条消息,一般用于文件上传;
• Content-Type:application/octet-stream
提交二进制数据,如果用于文件上传,只能上传一个文件;
• Content-Type:application/json
提交json数据
提交多个文件

java 复制代码
@Test
public void uploadFileTest() throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        File file1 = new File("H:\\Users\\ASUS\\Desktop\\f1.txt");
        File file2 = new File("H:\\Users\\ASUS\\Desktop\\f2.txt");

        MultipartBody multipartBody = new MultipartBody.Builder()
                .addFormDataPart("f1", file1.getName(), RequestBody.create(file1, MediaType.parse("text/plain")))
                .addFormDataPart("f2", file2.getName(), RequestBody.create(file2, MediaType.parse("text/plain")))
                .build();
        Request request = new Request.Builder().url("https://httpbin.org/post").post(multipartBody).build();
        Call call = okHttpClient.newCall(request);
        Response response = call.execute();
        System.out.println(response.body().string());
    }

提交json数据

java 复制代码
@Test
public void jsonTest() throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), "{\"a\":1,\"b\":2}");
        Request request = new Request.Builder().url("https://httpbin.org/post").post(requestBody).build();
        Call call = okHttpClient.newCall(request);
        Response response = call.execute();
        System.out.println(response.body().string());
    }
4.Builder构建者

OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
拦截器
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor( new XXX ).build();
OkHttpClient okHttpClient = new OkHttpClient.Builder().addNetworkInterceptor( new XXX ).build();

java 复制代码
@Test
    public void interceptorTest() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
            @NonNull
            @Override
            public Response intercept(@NonNull Chain chain) throws IOException {
                //请求前置处理
                Request request = chain.request().newBuilder()
                        .addHeader("os", "android")
                        .addHeader("version", "1.0")
                        .build();
                Response response = chain.proceed(request);
                //请求后置处理
                return response;
            }
        }).addNetworkInterceptor(new Interceptor() {    //一定先执行addInterceptor后执行addNetworkInterceptor  添加顺序不影响执行
            @NonNull
            @Override
            public Response intercept(@NonNull Chain chain) throws IOException {
                System.out.println("version" + chain.request().header("version"));
                return chain.proceed(chain.request());
            }
        }).build();

        Request request = new Request.Builder().url("https://httpbin.org/get?a=1&b=2").build();
        //准备好请求的call对象
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

缓存与 Cookie
OkHttp按照Http协议规则实现了缓存的处理,缓存是比如:当我们发起第一次请求之后,如果后续还需要进行同样的请求,此时如果符合缓存规则,则可以减少与服务器的网络通信,直接从本地文件缓存中读取响应返回给请求者。但是默认情况下,OkHttp的缓存是关闭状态,需要我们开启。

java 复制代码
OkHttpClient okHttpClient = new OkHttpClient.Builder().cache(new Cache(new File("/path/cache"),100))

Cookie是某些网站为了辨别用户身份,进行会话跟踪(比如确定登陆状态)而储存在用户本地终端上的数据(通常经过加密),由用户客户端计算机暂时或永久保存的信息

java 复制代码
Map<String, List<Cookie>> cookie = new HashMap<>();

    @Test
    public void cookieTest() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .cookieJar(new CookieJar() {
                    @Override
                    public void saveFromResponse(@NonNull HttpUrl httpUrl, @NonNull List<Cookie> list) {
                        cookie.put(httpUrl.host(), list);            //保存cookie
                    }

                    @NonNull
                    @Override
                    public List<Cookie> loadForRequest(@NonNull HttpUrl httpUrl) {
                        List<Cookie> cookies = cookie.get(httpUrl.host());  
                        return cookies == null ? new ArrayList<>() : cookies;    //加载并返回cookie
                    }
                }).build();
        FormBody formBody = new FormBody.Builder().add("username", "xx").add("password", "xxxxxx").build();
        Request request = new Request.Builder().url("https://www.xxx.com/user/login").post(formBody).build();

        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
相关推荐
千里马学框架4 天前
一起学 Android 14:ShellTransition 屏幕旋转过程深度剖析
android·智能手机·性能优化·framework·性能·屏幕旋转·rotation
美狐美颜SDK开放平台4 天前
开发直播APP时如何接入视频美颜SDK?开发流程与注意事项
android·人工智能·计算机视觉·音视频·直播美颜sdk
AFinalStone4 天前
Android7 SystemUI源码解析(七)Keyguard锁屏模块深度解析
android·systemui
致远ccc4 天前
Google Play 上架前如何测试 App?多国家 Android 环境测试
android·app测试·googleplay·多国家应用测试
ttyyttemo4 天前
Kotlin 协程中的 Job 结构化并发与取消
android
sun0077004 天前
tbox 4g/5g切换,导致wan ip 改变,导致车机旧网络不可用。需要重启车机才行
android
其实防守也摸鱼4 天前
内网穿透与反向代理:原理、工具与实战指南
android·大数据·运维·安全·网络安全·自动化·渗透
AFinalStone4 天前
Android7 SystemUI 源码解析(四)NavigationBar 导航栏与 SystemBars
android·systemui
JMchen4 天前
属性动画原理与高级动画实现
android·kotlin·canvas
AFinalStone4 天前
Android7 SystemUI 源码解析(二)启动流程深度解析
android·systemui