用Retrofit做GET请求,在onResponse()里面怎么才能获取到返回的JSON数据呢?

202005021116 应用层 2018-04-15 09:29:54
这个URL是可以正常访问的.打印出来的是对象地址值,我已经toString了. 也不能调用response.body.string方法.
1.NetWork.class
public class NetWork {
private static Retrofit retrofit;
/**返回Retrofit*/
public static Retrofit getRetrofit(){
if(retrofit==null){
Retrofit.Builder builder = new Retrofit.Builder();//创建Retrfit构建器
retrofit = builder.baseUrl("http://v.juhe.cn/") //指定网络请求的baseUrl
// retrofit = builder.baseUrl("http://v.juhe.cn/") //指定网络请求的baseUrl
.addConverterFactory(GsonConverterFactory.create())//返回的数据通过Gson解析
.build();
}
return retrofit;
}
}


2.NetInterface.class
public interface NetInterface {
// @GET("mobile/get")
@GET("toutiao/index?type=top&key=c727cca6fb450ea08b4b0fa220b72eb1")
// @GET("toutiao/index")
Call<Bean> getDatas();
}


3.Bean.class
public class Bean {

private String reason;
public String phone;
public String key;
private String error_code;

public String getError_code() {
return error_code;
}

public void setError_code(String error_code) {
this.error_code = error_code;
}

public String getReason() {
return reason;
}

public void setReason(String reason) {
this.reason = reason;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public String getKey() {
return key;
}

public void setKey(String key) {
this.key = key;
}
}


4.MainActivity.class
    private void doTest() {
//初始化Retrofit,加载接口
NetInterface netInterface = NetWork.getRetrofit().create(NetInterface.class);
netInterface.getDatas()
.enqueue(new Callback<Bean>() {
@Override
public void onResponse(Call<Bean> call, Response<Bean> response) {
//请求成功
Bean bean = response.body();
String json = response.body().toString();
Log.d(TAG, "2336= " + json);//这里打印的是com.b.demo8.Bean@8463c78
String reason = bean.getReason();
String error_code = bean.getError_code();
// Log.d(TAG, "2319= "+reason);
// String message = response.message();
// Log.d(TAG, "2327= "+message);
// Log.d(TAG, "2312= "+error_code);
// Log.d(TAG, "2304= "+json);
}

@Override
public void onFailure(Call<Bean> call, Throwable t) {
//请求失败
Log.d(TAG, "onFailure: ");
}
});
}
...全文
1570 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
cattpon 2018-04-16
  • 打赏
  • 举报
回复
引用 1 楼 z979451341 的回复:
Retrofit在创建的时候可以设置Gson自动转啊,https://blog.csdn.net/haveferrair/article/details/51499274
正解~
键盘舞者113 2018-04-15
  • 打赏
  • 举报
回复
Retrofit在创建的时候可以设置Gson自动转啊,https://blog.csdn.net/haveferrair/article/details/51499274

80,359

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧