初识Retrofit(-)

刚刚接触Retrofit,一时有点懵比,跟着→这位作者,一点点开始了,先成功实现了实现了一个完整的Get请求。之后在进一步继续学习。本人是刚接触这个,请大家多多赐教。(^-^

再一次说明,参考了这位作者→召唤师技能:传送

一个整Get请求的实现:

先添加依赖

 compile 'com.squareup.retrofit2:retrofit:2.2.0'
 compile 'com.squareup.retrofit2:converter-gson:2.2.0'

1.创建业务请求接口:

public interface GetZipCodeInfoService {
  public interface GetZipCodeInfoService {
    @GET("query")
    Call<ZipCodeInfo> getInfo(@Query("postcode") String postcode,@Query("key") String key);
}
  //@Query("postcode") String name 就相当与在"query"后面拼接参数,拼接后为
  //"query?postcode=postcode?key=key"
  //等同于@GET("query?postcode=postcode?key=key")
}

2.创建Retrofit实例,完成相关的配置:

Retrofit retrofit = new Retrofit.Builder()
   .baseUrl("http://v.juhe.cn/postcode/")
   .addConverterFactory(GsonConverterFactory.create())
   .build();
GetZipCodeInfoService service = retrofit.create(GetZipCodeInfoService.class);
//这里的baseUrl就是网络请求URL相对固定的地址

3.调用请求方法,得到Call的实例:

Call<ZipCodeInfo> call = service.getInfo("215001",AppKey);
//通过调用接口GetZipCodeInfoService的getInfo()方法,传递相应的参数,得到Call的实例。

4.通过使用Call实例,完成数据的请求

call.enqueue(new Callback<ZipCodeInfo>() {
            @Override
            public void onResponse(Call<ZipCodeInfo> call, Response<ZipCodeInfo> response) {
                if(response!=null){
                    list=response.body().getResult().getList();
                    textView.setText(list.get(1).getAddress());
                }
            }
            @Override
            public void onFailure(Call<ZipCodeInfo> call, Throwable t) {

            }
        });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值