okhttp3的使用

okhttp3的使用

 

目录

1. 简介
2. 依赖
3. 混淆
4. GET请求
5. POST请求: 提交Form表单
6. POST请求: 提交Json数据

 

简介

okhttp官网: http://square.github.io/okhttp/
okio官网: https://github.com/square/okio

 

依赖

implementation 'com.squareup.okhttp3:okhttp:3.11.0'

 

混淆

# Okhttp3的混淆配置
# JSR 305 annotations are for embedding nullability information.
-dontwarn javax.annotation.**
# A resource is loaded with a relative path so the package of this class must be preserved.
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
# Animal Sniffer compileOnly dependency to ensure APIs are compatible with older versions of Java.
-dontwarn org.codehaus.mojo.animal_sniffer.*
# OkHttp platform used only on JVM and when Conscrypt dependency is available.
-dontwarn okhttp3.internal.platform.ConscryptPlatform

 

GET请求

//创建OkHttpClient对象
OkHttpClient okHttpClient  = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10,TimeUnit.SECONDS)
        .readTimeout(20, TimeUnit.SECONDS)
        .build();

//请求的url
String requestUrl = "http://www.geaosu.com/app/user/updatainfo?userName=geaosu";

final Request request = new Request.Builder()
        .url(requestUrl)    //请求地址
        .get()              //设置请求方式: get()方式和post()方式, 默认请求方式为GET
        .build();           //构建一个请求Request对象

//创建Call
Call call = okHttpClient.newCall(request);

//加入队列 异步操作
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        //请求失败的监听: 异步请求(非主线程)
        System.out.println("连接失败");
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        //请求成功的监听: 异步请求(非主线程)
        if(response.code()==200) {
            System.out.println(response.body().string());
        }
});

 

POST请求: 提交Form表单

//构造OkHttpClient对象
OkHttpClient okHttpClient  = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10,TimeUnit.SECONDS)
        .readTimeout(20, TimeUnit.SECONDS)
        .build();

//配置POST要提交的数据 --> FormBody
FormBody formBody = new FormBody.Builder()
        .add("userName", "geaosu")
        .add("userMail", "geaosu@163.com")
        .build();

//请求地址
String requestUrl = "http://www.geaosu.com/app/user/updatainfo";

//构造请求
final Request request = new Request.Builder()
        .url()
        .post(formBody)
        .build();

//构造Call
Call call = okHttpClient.newCall(request);

//加入请求队列
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        //请求失败监听: 异步请求(非主线程)
        System.out.println("连接失败");
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        //请求成功监听: 异步请求(非主线程)
        if(response.code()==200) {
            System.out.println(response.body().string());
        }
    }
});

 

POST请求: 提交Json数据

//构造okhttp客户端
OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .readTimeout(20, TimeUnit.SECONDS)
        .build();

//配置参数: json数据(key和value)
HashMap<String, String> map = new HashMap<>();
map.put("userQQ", "819813992");
map.put("userName", "geaosu");
map.put("userMail", "geaosu@163.com");
map.put("userWeChat", "geaosu");

//将map转成json字符串
Gson gson = new Gson();
String json = gson.toJson(map);
//转换结果: "{"userWeChat":"geaosu","userQQ":"819813992","userName":"geaosu","userMail":"geaosu@163.com"}"

//MediaType  设置Content-Type 标头中包含的媒体类型值
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json);

//请求地址
String url = "http://www.geaosu.com/app/user/updatainfo";

//构造请求
Request request = new Request.Builder()
        .url(url)               //请求地址
        .post(requestBody)      //请求方式: POST
        .build();

//创建Call
Call call = okHttpClient.newCall(request);

//加入请求队列
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        //请求失败监听: 异步请求(非主线程)
        System.out.println("连接失败");
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        //请求成功监听: 异步请求(非主线程)
        System.out.println(response.body().string());
    }
});

 

华丽的分割线 --------------------------------------------------------------------------------->> 完

posted @ 2018-10-24 16:20  geaosu  阅读(2634)  评论(0编辑  收藏  举报