1.添加依赖
//熟悉rx和retrofit2 compile "io.reactivex:rxjava:1.2.3" compile 'io.reactivex:rxandroid:1.2.1' compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0' compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0' compile 'com.jakewharton.rxbinding:rxbinding:1.0.0'2.bean类 根据返回的js利用gsonformat生成 3.定义接口
public interface Server { //没有头 //cart 子节点 //@FormUrlEncoded,当有参数时,post必加 //"sku" 参数名称 //Call<Bean> post Bean回调泛型 post方法名 @POST("cart") @FormUrlEncoded Call<Bean> post(@Field("sku") String url); //有头没参数 @POST("logout") Call<TC> post1(@Header("userid") String userid); //有头有参数 @POST("checkout") @FormUrlEncoded Call<TJ> post(@Header("userid") String userid,@Field("sku") String sku); //没有头 //login 子节点 //"username" 参数名称 //"passWord" 参数名称 @GET("login") Call<User> get(@Query("username") String username, @Query("password") String password); @GET("userinfo") Call<UserInfo> get(@Header("userid") String username); //有头有参数 //@Header("userid") userid 头名称 //favorites 子节点 //"username" 参数名称 //"password" 参数名称 @GET("favorites") Call<SC> get(@Header("userid") String userid,@Query("page") String page, @Query("pageNum") String pageNum);}4.初始化 该部分可以在application下初始化
HOST为公共节点Retrofit retrofit = new Retrofit.Builder() .baseUrl(HOST) // 注意下面这行,把原来的Call结果,变为了Obserable结果 //.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); final Server mServer = retrofit.create(Server.class);5.调用
mServer.post("1:3:1,3").enqueue(new Callback<Bean>() { @Override 成功的回调 public void onResponse(Call<Bean> call, Response<Bean> response) { Log.d("MainActivity", response.body().getCart().get(0).getPRoduct().getName()); } 失败的回调 @Override public void onFailure(Call<Bean> call, Throwable throwable) { } });新闻热点
疑难解答