项目一直在用okgo,新项目打算使用retrofit,看了一下,自己记录一下基本使用。。。
1.首先单例一个Retrofit
public class RetrofitUtils
{
public static Retrofit retrofit;
public static final String END_POINT = "xxxxx";
public static Retrofit getRetrofit()
{
if (retrofit == null)
{
retrofit = new Retrofit.Builder()
.baseUrl(END_POINT) //设置网络请求的Url地址
// .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
}
return retrofit;
}
}
END_POINT 就是你后台接口网址里重复存在的内容,类似www.baidu.com,github.com,这里仅设置一个baseurl
2.每一个api对应一个interface——get/post请求
retrofit的复杂点就在与这个Interface,和里面的一堆注解,我这边只简单弄了些get/post请求
①.post请求
public interface Login
{
@FormUrlEncoded
@POST("driver/driverLogin")
Call<ResponseBody> login(@FieldMap Map<String, String> map);
}
@FormUrlEncoded、@POST和@FieldMap是必须写上的,其中@POST后面括号里的内容是你这个接口网址,加上你的baseurl,你整个的接口url就变成
String url = END_POINT + "driver/driverLogin";
而上面的login,这个是随便写的,比如我这个接口的功能是登录,于是就叫login
具体调用:(interface我全部写在Api.class里)
Api.Login login = retrofit.create(Api.Login.class);
HashMap<String, String> map = new HashMap<>();
map.put("phone", "18512345678");
Call<ResponseBody> call = login.login(map);
call.enqueue(new Callback<ResponseBody>()
{
@Override
public void onResponse(Call<ResponseBody>