我正在使用改造将json对象发送到服务器,试图创建用户,我正在发送此json对象 {"apellido":"prueba","email":"[email protected]","fechaDeNacimiento":"11/29/1998","formaDeRegistro":"Android","nombre":"prueba","password":"12345678","username":"prueba"}
在此示例中,我创建了一个无效的用户,因此服务器响应带有json对象,其中将其代码错误编码为代码,并向其发送错误的信息
[{"code":"5","message":"The email is in use"}]
接口
public interface UserClient {
@POST("usuarios")
Call<Usuarios> create(@Body Usuarios usuario);
}
资料模型
import com.google.gson.annotations.SerializedName;
public class Usuarios {
@SerializedName("username")
String username;
@SerializedName("email")
String email;
@SerializedName("password")
String password;
@SerializedName("nombre")
String nombre;
@SerializedName("apellido")
String apellido;
@SerializedName("fechaDeNacimiento")
String fechaDeNacimiento;
@SerializedName("formaDeRegistro")
String formaDeRegistro;
String message;
public Usuarios(String email, String username, String password, String nombre, String apellido, String fechaDeNacimiento, String formaDeRegistro){
this.username=username;
this.email=email;
this.password=password;
this.nombre = nombre;
this.apellido= apellido;
this.fechaDeNacimiento = fechaDeNacimiento;
this.formaDeRegistro = formaDeRegistro;
}
public String getMessage(){
return message;
}
}
和改造工具
OkHttpClient.Builder okhttpClientBuilder=new OkHttpClient.Builder();
HttpLoggingInterceptor loggin=new HttpLoggingInterceptor();
loggin.setLevel(HttpLoggingInterceptor.Level.BODY);
okhttpClientBuilder.addInterceptor(loggin);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("https://intense-lake-39874.herokuapp.com")
.addConverterFactory(GsonConverterFactory.create())
.client(okhttpClientBuilder.build());
Retrofit retrofit = builder.build();
UserClient service = retrofit.create(UserClient.class);
Call<Usuarios> call = service.create(usuario);
call.enqueue(new Callback<Usuarios>() {
@Override
public void onResponse(Call<Usuarios> call, Response<Usuarios> response) {
Toast.makeText(Main2Activity.this,"Usuario Registrado! "+response.body().getMessage,Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<Usuarios> call, Throwable t) {
Toast.makeText(Main2Activity.this,"Algo fallo..",Toast.LENGTH_SHORT).show();
}
});
}
因此,我可以看到logcat的响应,但在主体中它指定为null,我如何获得“消息”?
该错误是因为您的响应未成功,因此您需要解析错误正文,请尝试使用以下代码:
if (response.isSuccessful()) {
// Do your success stuff...
} else
{
try
{
JSONObject jObjError = new JSONObject(response.errorBody().string());
Toast.makeText(getContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
当然,您可以使用其他解析器,例如Gson。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句