Retroift简单二次封装
retrofit 的简单二次封装
基于上次的retrofit 初探后,可以对 retrofit 简单的二次封装
public interface HttpURL {
String baseUrl = "http://127.0.0.1:32001/";
}
public class RequestUtils {
private static OkHttpClient client;
private static Retrofit retrofit;
private RequestUtils() {
}
static {
client = new OkHttpClient()
.newBuilder()
.connectTimeout(8, TimeUnit.SECONDS)
.readTimeout(8, TimeUnit.SECONDS)
.writeTimeout(8, TimeUnit.SECONDS)
.addInterceptor(new HttpInterceptor())
.build();
retrofit = new Retrofit.Builder()
.baseUrl(HttpURL.baseUrl)
.client(client)
.addConverterFactory(StringConverterFactory.create())
.build();
}
public static String post(String url, String body) throws IOException {
RequestServer requestServer = retrofit.create(RequestServer.class);
String[] path = url.split("/");
Call<String> call = requestServer.post(path[0], path[1], body);
Response<String> response = call.execute();
return response.body();
}
public static void main(String[] args) throws IOException {
String hello = post("ping/test", "hello");
System.out.println(hello);
}
}
输出结果
{ "code": 200, "content": { "msg": "成功" } }
这里的 post 方法就是传入 url,请求参数是 body,返回值就是 String 类型,如果需要对 string,如果需要对返回值进行处理,再接受 hello 的对应参数进行处理即可
同样的道理,现在很多的网站可以使用 put/delete/get/post 等不同的 method 方法在同一个 URL 下区分不同的业务逻辑和返回值,只要进行对应的封装即可