准备工作
在上一篇博客 网络请求(三)——Retrofit的get和post请求的用法 中,每日一词的json格式比较简单,于是试了一下使用API的查词接口
我使用的API
http://dict-co.iciba.com/api/dictionary.php?w=good&type=json&key=0CD3A4C079D2D23C683BBFF96300E924
JSON结构
代码
一开始,事情进行的很顺利……
- 新建用于接收服务器返回数据的类,新建接口
public interface GetRequest_Interface {
//用get方式发送网络请求
@GET("api/dictionary.php?w=go&type=json&key=0CD3A4C079D2D23C683BBFF96300E924")
//接收网络请求数据的方法
Call<Translation> getCall();
@POST("api/dictionary.php?")
Call<Translation> postCall(
@Query("w") String word, @Query("type") String type, @Query("key") String key);
}
- 创建Retrofit实例
System.out.println(translation.getSymbols().get(0).getParts().get(0).getMeans().get(0));
- 这句中,先得到"Symbols",再get(0)获得数组第一个参数([ ]里的),得到"Parts",get(0)获取第一个参数,得到"Means",再获得第一个中文意思
private void request() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://dict-co.iciba.com/")
.addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析
.build();
GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
Call<Translation> call = request.getCall();
call.enqueue(new Callback<Translation>() {
@Override
public void onResponse(Call<Translation> call, Response<Translation> response) {
if(response.isSuccessful()) {
Translation translation = response.body();
System.out.println(translation.