Retrofit超简单demo

1.定义个接口

public interface ShopService {
    @GET("/course_api/wares/hot")
    Call<ShopBean> getShop(@Query("pageSize") int pageSize,
                           @Query("curPage") int curPage);
}
这里写明了使用get还是post
 @Query("curPage")

传入的参数

其中Query 是作为url的参数的,使用时类似” user/john?password=xxxx"这样,而Path是用来替换你路径里的条目的,类似“user/{username}”
2.定义个bean对象,Gson
/**
 * error_code : 0
 * reason : Success
 * result : {"data":[{"content":"几千年后,一群考古学家挖掘出起点中文网的服务器并恢复出信息,由于文明形态的差异,他们会惊异地发现,早在千年前那个科技极度落后的时代,古地球文明已经拥有了【肉身可以横渡宇宙,一拳能够打爆星球】的强者,而且为数不少,因为在服务器里有上万本内容近似但名字不同的人物传记,这又能证明这种方法已经广泛应用。考古学家们为古地球人的伟力震惊,又为这种强悍的【修炼】方法失传而惋惜。","hashId":"9a05858007372df8ab297f104c047420","unixtime":1488518030,"updatetime":"2017-03-03 13:13:50"}]}
 */

private int error_code;
private String reason;

public int getError_code() {
    return error_code;
}

public void setError_code(int error_code) {
    this.error_code = error_code;
}

public String getReason() {
    return reason;
}

public void setReason(String reason) {
    this.reason = reason;
}
3.在activity中
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://112.124.22.238:8081/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

ShopService service = retrofit.create(ShopService.class);
//pageSize = 10,curPage=1
Call<ShopBean> callShops = service.getShop(10,1);

callShops.enqueue(new Callback<ShopBean>() {
    @Override
    public void onResponse(Call<ShopBean> call, Response<ShopBean> response) {
            Log.e("response",response.toString());
    }

    @Override
    public void onFailure(Call<ShopBean> call, Throwable t) {
        Log.e("failure","fail");
    }
});
总共出现三处url,其中base+Get+传入参数

猜你喜欢

转载自blog.csdn.net/qq_30711091/article/details/80804582