OkHttp学习笔记

发表于 2020-05-20
阅读 40

介绍

介绍

OkHttp是 Android 开发界最受欢迎的网络编程的库

今天我们就来学习它的使用方法和技巧

教程

导入

添加依赖

打开 Gradle scripts -> build.gradle (Module: app)

在 android 里添加如下设定

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

在 dependencies 里添加如下依赖项目

implementation 'com.squareup.okhttp3:okhttp:3.14.2'
implementation 'com.squareup.okio:okio:1.17.4'

点击右上角的 Sync Now 下载库

使用

完成 GET 请求

我们来写一段简单的代码来完成GET请求

OkHttpClient httpClient;
Request request;
Call call;
Response response;

try{
    httpClient = new OkHttpClient();
    request = new Request.Builder()
            .url("https://tongfu.net/api/user/logined/_loginUser")
            .get()
            .build();
    call = httpClient.newCall(request);
    response = call.execute();
    if(response.code() == 200){
        System.out.println(response.body().string());
    }
}
catch (IOException e){
    e.printStackTrace();
}
catch (Exception e){
    e.printStackTrace();
}

完成POST请求

我们来写一段简单的代码来模拟POST请求

表单提交

使用FormBody.Builder创建请求体,可以通过add方法一个一个地将POST数据传入进来,这种方式模拟的是网页表单提交的效果。

OkHttpClient httpClient;
RequestBody body;
Request request;
Call call;
Response response;

try{
    httpClient = new OkHttpClient();
    body = new FormBody.Builder()
            .add("uid", "35")
            .add("oldPwd", "123456")
            .add("newPwd", "abcdef")
            .add("confirmPwd", "abcdef")
            .build();
    request = new Request.Builder()
            .url("https://tongfu.net/api/user/logined/_passwd")
            .post(body)
            .build();
    call = httpClient.newCall(request);
    response = call.execute();
    if(response.code() == 200){
        System.out.println(response.body().string());
    }
}
catch (IOException e){
    e.printStackTrace();
}
catch (Exception e){
    e.printStackTrace();
}

JSON提交

使用RequestBody.create方法可以指定请求类型,这里福哥通过RequestBody.create提交了一段JSON数据到服务器上,这种方法模拟的是网页的AJAX请求的方式。

OkHttpClient httpClient;
RequestBody body;
Request request;
Call call;
Response response;
JSONObject json;
String jsonData;

try{
    httpClient = new OkHttpClient();
    json = new JSONObject();
    json.put("uid", 35);
    json.put("oldPwd", "123456");
    json.put("newPwd", "abcdef");
    json.put("confirmPwd", "abcdef");
    jsonData = json.toString();
    body = RequestBody.create(MediaType.parse("application/json"), jsonData);
    request = new Request.Builder()
            .url("https://tongfu.net/api/user/logined/_passwd")
            .post(body)
            .build();
    call = httpClient.newCall(request);
    response = call.execute();
    if(response.code() == 200){
        System.out.println(response.body().string());
    }
}
catch (IOException e){
    e.printStackTrace();
}
catch (Exception e){
    e.printStackTrace();
}

实现上传文件请求

写一段简单的代码模拟用户选择图片上传到服务器的操作,这里面需要有内存卡访问权限

OkHttpClient httpClient;
RequestBody body;
Request request;
Call call;
Response response;

try{
    httpClient = new OkHttpClient();
    body = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("uid", "35")
            .addFormDataPart("file", "photo.jpg",
                    RequestBody.create(MediaType.parse("image/jpeg"), new File("/mnt/sdcard/Pictures/photo.jpg")
                    ))
            .build();
    request = new Request.Builder()
            .url("https://tongfu.net/api/user/logined/_icon")
            .post(body)
            .build();
    call = httpClient.newCall(request);
    response = call.execute();
    if(response.code() == 200){
        System.out.println(response.body().string());
    }
}
catch (IOException e){
    e.printStackTrace();
}
catch (Exception e){
    e.printStackTrace();
}

注意:OkHttpClient 请求不能在主线程里进行,所以我们需要把这些逻辑放入 Thread 里去运行

总结

福哥今天将使用OkHttp工具来模拟HTTP协议的GET、POST请求的操作。当然,除了这两个请求方式外还有诸如:PUT、DELETE、HEAD等等方法,这个就留给大家自己探索吧!

鬼谷子叔叔

跟福哥学编程吧~~
日志
212
浏览
1626