Retrofit2,简单使用测试
接口定义:
public interface RetrofitWeatherService {
@GET("data/sk/{cityId}.html")
Call<ResponseBody> getWeatherInfo(@Path("cityId") String cityId);
}
调用测试:
public class RetrofitServiceMain {
public static void main(String[] args) throws IOException {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.weather.com.cn/")
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitWeatherService subService = retrofit.create(RetrofitWeatherService.class);
Call<ResponseBody> call = subService.getWeatherInfo("101010100");
ResponseBody info = call.execute().body();
System.out.println(info.string());
System.out.println("异步方式调用:");
Call<ResponseBody> asynCall = call.clone(); // 因为call只能使用一次,所以如果想多次数用,可以使用clone()新建一个对象;
asynCall.enqueue(new Callback<ResponseBody>() {
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
}
输出内容:
{"weatherinfo":{"city":"北京","cityid":"101010100","temp":"18","WD":"东南风","WS":"1级","SD":"17%","WSE":"1","time":"17:05","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1011","rain":"0"}}
返回实体定义:
public class WeatherInfo {
private String city;
private String cityid;
private String temp;
private String WD;
private String WS;
private String SD;
private String WSE;
private String time;
private String isRadar;
private String Radar;
private String njd;
private String qy;
private String rain;
// get set 方法略
@Override
public String toString() {
return "WeatherInfo{" +
"city='" + city + '\'' +
", cityid='" + cityid + '\'' +
", temp='" + temp + '\'' +
", WD='" + WD + '\'' +
", WS='" + WS + '\'' +
", SD='" + SD + '\'' +
", WSE='" + WSE + '\'' +
", time='" + time + '\'' +
", isRadar='" + isRadar + '\'' +
", Radar='" + Radar + '\'' +
", njd='" + njd + '\'' +
", qy='" + qy + '\'' +
", rain='" + rain + '\'' +
'}';
}
}
问题集锦:
Q:Caused by: java.lang.IllegalArgumentException: Could not locate ResponseBody converter for.....
A:主要是因为序列化组件缺失造成序列化失败;解决方案就是引入对应的组件即可;retrofit支持jackson、gson、protobuffer、moshi等;
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.squareup.retrofit2/converter-gson -->
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>2.1.0</version>
</dependency>
Q:java.lang.IllegalArgumentException: Service methods cannot return void
A:修改Service层返回值为Call类型,并调用Call.execute()或者Call.enqueue(CallBack)方法。
点滴积累,每天进步一点点!O(∩_∩)O~