Retrofit和okhtttp都共同出自square公司。retrofit就是对OKHttp做了封装。retrofit最大的优点就是解耦,解构就需要大量的设计模式。
retrofit使用分以下几步:
第一,创建接口:请求方式,请求函数,请求的方法,以及参数。
其中:@post:说明请求方法是post,(“mobileLogin/submit.html”)资源的部分URL,
@Query是post请求上送的参数@Query("loginname")是上送的键,String loginname是传入的值。@Path是第二种地址书写方式。
public interface RequestServes { @POST("mobileLogin/submit.html") Call<String> getString(@Query("loginname") String loginname, @Query("nloginpwd") String nloginpwd); }"{name}") (
Call<User>getUser(@Path("name") String name);
第二,创建Retrofit对象。
其中:"http://106.3.227.33/pulamsi/"+上面的“mobielogin/submit.html”构成请求的全部地址。
Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://106.3.227.33/pulamsi/") //增加返回值为String的支持 .addConverterFactory(ScalarsConverterFactory.create()) //增加返回值为Gson的支持(以实体类返回) .addConverterFactory(GsonConverterFactory.create()) //增加返回值为Oservable<T>的支持 .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build();
第三,创建引用并执行请求方法。
RequestSerives requestSerives = retrofit.create(RequestSerives.class);//这里采用的是Java的动态代理模式 Call<String> call = requestSerives.getString("userName", "1234");//传入我们请求的键值对的值 |
call.enqueue(new Callback<String>() { public void onResponse(Call<String> call, Response<String> response) { Log.e("===","return:"response.body().toString()); } public void onFailure(Call<String> call, Throwable t) { Log.e("===","失败"); } });