80,359
社区成员
发帖
与我相关
我的任务
分享
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;
}
}
public interface NetInterface {
// @GET("mobile/get")
@GET("toutiao/index?type=top&key=c727cca6fb450ea08b4b0fa220b72eb1")
// @GET("toutiao/index")
Call<Bean> getDatas();
}
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;
}
}
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: ");
}
});
}