Retroift简单二次封装

文章目录

retrofit 的简单二次封装

基于上次的后,可以对 retrofit 简单的二次封装

1public interface HttpURL {
2    String baseUrl = "http://127.0.0.1:32001/";
3}
 1public class RequestUtils {
 2
 3    private static OkHttpClient client;
 4    private static Retrofit retrofit;
 5
 6    private RequestUtils() {
 7    }
 8
 9    static {
10        client = new OkHttpClient()
11                .newBuilder()
12                .connectTimeout(8, TimeUnit.SECONDS)
13                .readTimeout(8, TimeUnit.SECONDS)
14                .writeTimeout(8, TimeUnit.SECONDS)
15                .addInterceptor(new HttpInterceptor())
16                .build();
17
18        retrofit = new Retrofit.Builder()
19                .baseUrl(HttpURL.baseUrl)
20                .client(client)
21                .addConverterFactory(StringConverterFactory.create())
22                .build();
23    }
24
25    public static String post(String url, String body) throws IOException {
26        RequestServer requestServer = retrofit.create(RequestServer.class);
27        String[] path = url.split("/");
28        Call<String> call = requestServer.post(path[0], path[1], body);
29        Response<String> response = call.execute();
30        return response.body();
31    }
32
33    public static void main(String[] args) throws IOException {
34        String hello = post("ping/test", "hello");
35        System.out.println(hello);
36    }
37}

输出结果

1{ "code": 200, "content": { "msg": "成功" } }

这里的 post 方法就是传入 url,请求参数是 body,返回值就是 String 类型,如果需要对 string,如果需要对返回值进行处理,再接受 hello 的对应参数进行处理即可

同样的道理,现在很多的网站可以使用 put/delete/get/post 等不同的 method 方法在同一个 URL 下区分不同的业务逻辑和返回值,只要进行对应的封装即可