一.Retrofit的介绍
retrofit同样是一款由Square公司开发的网路库,上次说的okhttp是一种更接近底层通信的一种使用,而现在的retrofit更加简洁,它是侧重于对功能接口的封装。retrofit是在okhttp基础上进一步开发出来的应用层网络通信库,使我们更加好的理解去进行网路请求。Retrofit官方地址是:https://github.com/square/retrofit
二.Retrofit的基础使用
首先先去官网找到最新的依赖,加入到我们的build.gradle中去
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
首先假设我们请求的网页基本域名是 https://www.xxx/
接口有 1.post : https://www.xxx/postName
参数 : name,password
2.get : https://www.xxx/getName
参数 : name, password
接着我们定义一个接口HttpUtils:
public interface HttpUtils {
@GET("getName")
Call<ResponseBody> getLoginMessage(@Query("name")String username,@Query("password") String userpassword);
@POST("postName")
@FormUrlEncoded
Call<ResponseBody> postLoginMessege(@Field("name") String username,@Field("password") String userpwd);
}
。。。类中使用方法
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.xxx/ ").build();
HttpUtils httpUtils = retrofit.create(HttpUtils.class);
Call<ResponseBody> abc = httpUtils.getLoginMessage("123", "abc");
abc.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
- @