刚刚接触Retrofit,一时有点懵比,跟着→这位作者,一点点开始了,先成功实现了实现了一个完整的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) { } });