第一步,导包
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'//Retrofit2所需要的包
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'//ConverterFactory的Gson依赖包
compile 'com.squareup.retrofit2:converter-scalars:2.0.0-beta4'//ConverterFactory的String依赖包
请求方式: Retrofit提供的请求方式注解有@GET
和@POST
第二步,
与Okhttp不同的是,Retrofit需要定义一个接口,用来返回我们的Call对象,这里示范的是Post请求:
public interface RequestServes { @POST("mobileLogin/submit.html") Call<String> getString(@Query("loginname") String loginname, @Query("nloginpwd") String nloginpwd); }
@PATH
通过参数填充完整路径
@GET("{name}")
Call<User> getUser(@Path("name") String name);
@Query
我们请求的键值对的设置,我们构建call对象的时候会传入此参数
@POST("mobileLogin/submit.html") Call<String> getString(@Query("loginname") String loginname, @Query("nloginpwd") String nloginpwd);
接口定义完,要用Restrofit对象来请求了
创建一个Retrofit 对象
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();
这里的baseUrl
加上之前@POST("mobileLogin/submit.html")
定义的参数形成完整的请求地址;
ddConverterFactory(ScalarsConverterFactory.create())
的意思是构建了一个返回支持,如果你的Call对象的泛型接收另外的格式需要添加另外的支持
接下来我们用这个Retrofit
对象创建一个RequestSerives
接口对象,也就是我们之前定义的那个接口,并且得到我们的Call对象;
| RequestSerives requestSerives = retrofit.create(RequestSerives.class);//这里采用的是Java的动态代理模式 Call<String> call = requestSerives.getString("userName", "1234");//传入我们请求的键值对的值 利用得到的Call对象,然后我们就发出网络请求了:
call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { Log.e("===","return:"response.body().toString()); } @Override public void onFailure(Call<String> call, Throwable t) { Log.e("===","失败"); } }); |