Android冒险之旅-21-okhttp的使用与自定义接口监听

 

目录

1. 添加依赖

2. 简单封装

 2.1 工具类

 2.2 自定义回调接口

3. 五种常用请求方式

 3.1 无参GET请求

 3.2 有参GET请求

 3.3 无参POST请求

 3.4 有参POST请求

 3.5 传递Json参数

4. 后端

END


1. 添加依赖

    // Okhttp框架
    implementation 'com.squareup.okhttp3:okhttp:4.9.0'

2. 简单封装

 2.1 工具类

/**
 * create by 星航指挥官
 * create on 2020/11/26
 * 不过是大梦一场空
 * 课不过是孤影照惊鸿
 */
public class OkHttpUtil {
    private static OkHttpClient client = null;
    //创建Client对象
    private static void createClient() {
        if (client == null) {
            client = new OkHttpClient.Builder()
                    .readTimeout(5, TimeUnit.SECONDS)//设置读超时
                    .writeTimeout(5, TimeUnit.SECONDS)设置写超时
                    .connectTimeout(15, TimeUnit.SECONDS)//设置连接超时
                    .retryOnConnectionFailure(true)//是否自动重连
                    .build();
        }
    }
    /**
     * 发送请求
     * @param url  请求Url
     * @param body 请求体,如果有请求体则发送Post请求,否则发送Get请求
     * @param listener 自定义请求回调
     */
    public static void Request(String url, RequestBody body, RequestListener listener) {
        // 创建OkHttpClient对象
        createClient();
        Request request = null;
        if (body != null) {
            //发送Post请求
            request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
        } else {
            //发送Get请求
            request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
        }
        client.newCall(request).enqueue(new Callback() {
            //Success
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                listener.onSuccess(response.body().string());
            }

            //Failure
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                listener.onFailed(e.getMessage());
            }
        });
    }
    //String转为requestBody
    public static RequestBody stringToRequestBody(String stringBody){
        //String转RequestBody String、ByteArray、ByteString都可以用toRequestBody()
        MediaType mediaType=MediaType.Companion.parse("application/json;charset=utf-8");
        RequestBody requestBody=RequestBody.Companion.create(stringBody,mediaType);
        return requestBody;
    }
    //文件转为requestBody
    public static RequestBody fileToRequestBody(File file){
        //File转RequestBody
        MediaType mediaType=MediaType.Companion.parse("text/x-markdown; charset=utf-8");
        RequestBody fileBody=RequestBody.Companion.create(file,mediaType);
        return fileBody;
    }

}

 2.2 自定义回调接口

/**
 * create by 星航指挥官
 * create on 2020/11/24
 * 不过是大梦一场空
 * 课不过是孤影照惊鸿
 */
public interface RequestListener {

    /**
     * 请求成功回调
     *
     * @param result 服务器返回的数据
     */
    void onSuccess(String result);

    /**
     * 请求失败回调
     *
     * @param reason 失败原因
     */
    void onFailed(String reason);

}

3. 五种常用请求方式

 3.1 无参GET请求

        String url = "http://106.55.xxx.xxx:8080/yourInterface";
        OkHttpUtil.Request(url,null, new RequestListener() {
            @Override
            public void onSuccess(String data) {
                Log.e(TAG, "onSuccess: "+data);
            }

            @Override
            public void onFailed(String reason) {
                Log.e(TAG, "NOT Success: "+reason);
            }
        });

 3.2 有参GET请求

        String url = "http://106.55.xxx.xxx:8080/yourInterface";
        OkHttpUtil.Request(url+"?name=ALin&age=18",null, new RequestListener() {
            @Override
            public void onSuccess(String data) {
                Log.e(TAG, "onSuccess: "+data);
            }

            @Override
            public void onFailed(String reason) {
                Log.e(TAG, "NOT Success: "+reason);
            }
        });

 3.3 无参POST请求

        String url = "http://106.55.xxx.xxx:8080/yourInterface";
        //由于工具类封装的逻辑是 body!=null就发送POST请求 
        //所以我们new 一个RequestBody传过去 但不要添加具体参数即可
        OkHttpUtil.Request(url,new FormBody.Builder().build(), new RequestListener() {
            @Override
            public void onSuccess(String data) {
                Log.e(TAG, "onSuccess: "+data);
            }

            @Override
            public void onFailed(String reason) {
                Log.e(TAG, "NOT Success: "+reason);
            }
        });

 3.4 有参POST请求

        String url = "http://106.55.xxx.xxx:8080/yourInterface";
        RequestBody body = new FormBody.Builder()
                .add("name","alin")
                .add("age","3")
                .add("extra","阿林三岁半")
                .build();
        OkHttpUtil.Request(url,body, new RequestListener() {
            @Override
            public void onSuccess(String data) {
                Log.e(TAG, "onSuccess: "+data);
            }

            @Override
            public void onFailed(String reason) {
                Log.e(TAG, "NOT Success: "+reason);
            }
        });

 3.5 传递Json参数

        String url = "http://106.55.xxx.xxx:8080/yourInterface";
        JSONObject jsonParam = new JSONObject();
        try {
            jsonParam.put("name","ALin");
            jsonParam.put("age","22");
            jsonParam.put("extra","Everything is ok !");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //调用工具类中封装的方法将Json字符串转为RequestBody对象
        RequestBody body = OkHttpUtil.stringToRequestBody(jsonParam.toJSONString());

        OkHttpUtil.Request(url,body, new RequestListener() {
            @Override
            public void onSuccess(String data) {
                Log.e(TAG, "onSuccess: "+data);
            }

            @Override
            public void onFailed(String reason) {
                Log.e(TAG, "NOT Success: "+reason);
            }
        });

    }

4. 后端

SpringBoot后端接收参数的几种方式

END

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值