Retrofit超简单demo

这篇博客介绍了如何使用Retrofit进行网络请求。通过创建接口定义URL路径,使用Query和Path来处理参数,以及结合Gson进行数据解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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+传入参数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值