我刚学习Retrofit和Android开发。我想做的是从网站向服务器发送一个相当复杂的JSON对象,并能够使用Retrofit作为我的Android应用程序的Java对象来检索它。
所以基本上是这样的,
网站JSON --Ajax Call - >服务器 - 改造 - > Android应用程序(Java对象/集合)
哪个服务器最好设置它?关于如何做到这一点还有什么好的参考资料吗?
谢谢
答案 0 :(得分:1)
借助改造和android,您只需要几件事
Java模型
public class User {
private String name;
private String password;
public User(String name, String password) {
this.name = name;
this.password = password;
}
//Getters and setters
//...
}
改造界面
public interface APIService {
@FormUrlEncoded
@Headers("Accept: application/json")
@POST("register")
Call<AuthRegister> createUser(
@Field("name") String name,
@Field("password") String password
);
}
改装回调
public class AuthRegister {
@SerializedName("message")
@Expose
private String message;
@SerializedName("errors")
@Expose
private Errors errors;
public String getMessage() {
return message;
}
public Errors getErrors() {
return errors;
}
}
网络客户端
public class NetworkClient {
public static Retrofit retrofit;
/*
This public static method will return Retrofit client
anywhere in the appplication
*/
public static Retrofit getRetrofitClient() {
//If condition to ensure we don't create multiple retrofit instances in a single application
if (retrofit == null) {
//Defining the Retrofit using Builder
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.level(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
// .addInterceptor(interceptor)
.connectTimeout(30, TimeUnit.MINUTES)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(Config.BASE_URL) //This is the only mandatory call on Builder object.
.client(client)
.addConverterFactory(GsonConverterFactory.create()) // Convertor library used to convert response into POJO
.build();
}
return retrofit;
}
}
您要在活动中进行的呼叫以显示响应或保存数据
private void saveUser(String name, String password){
Retrofit retrofit = NetworkClient.getRetrofitClient();
APIService service = retrofit.create(APIService.class);
Call<AuthRegister> call = service.createUser(name, password);
call.enqueue(new Callback<AuthRegister>() {
@Override
public void onResponse(Call<AuthRegister> call, Response<AuthLogin> response) {
if (response.code() == 200) {
if (response.body().getMessage() != null) {
Toast.makeText(mContext, "Success", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, "Could not save user", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(mContext, "Could not save user", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<AuthRegister> call, Throwable t) {
new PrefManager(mContext).clearUser();
Log.e(TAG, t.toString());
Toast.makeText(mContext, "Could not save user", Toast.LENGTH_SHORT).show();
}
});
}
答案 1 :(得分:0)
您可以根据需要使用任何服务器。任何复杂的JSON都可以通过改造库来处理。请查看以下链接Retrofit android example web services