![](/img/trans.png)
[英]Receiving NULL on response error body if the status code is 400 with retrofit in android
[英]Retrofit2.0.0 beta getting null response body ,response code is 400
我是Retrofit的新手,我尝试在我的项目中实现Retrofit 2.0.0 beta。 为了注册用户,我尝试了Retrofit。 METHOD POST是,Content Type是application/x-www-form-urlencoded
。 我得到的响应为400,但响应正文为null
。 我在这里附上我的代码。
public interface MyApiInterface {
@Headers("Content-Type: application/x-www-form-urlencoded")
@FormUrlEncoded
@POST("/users/register")
Call<LoginResponse> doRegister(@Field("key") String value, @Field("key")
String value;
}
public class RestClient {
private static Retrofit REST_CLIENT;
private static MyApiInterface apiService;
public static String BASE_URL = "http://xx.xxx.xxx.xx:";
static {
setupRestClient();
}
public static MyApiInterface get() {
return apiService;
}
private static void setupRestClient() {
REST_CLIENT = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
apiService =
REST_CLIENT.create(MyApiInterface.class);
}
}
Call<Register> call = RestClient.get().doRegister("xxx",""xxxx);
call.enqueue(new Callback<Register>() {
@Override
public void onResponse(Response<Register> response, Retrofit retrofit) {
int statusCode = response.code();
LoginResponse user = response.body();
Log.d("String",statusCode+""+response.body() );
}
@Override
public void onFailure(Throwable t) {
}
});
我得到回应
{
status: "failed"
error_code: "invalid_client"
}
我的Register类是
public class Register {
public String status;
public String error_code;
}
您的后端似乎不支持默认的User-Agent
标头,并且需要特定的标头。 如果您未明确提供此标头,则我认为OkHttp将添加默认的User-Agent
,它是okhttp/version
(对此不确定(可以是System.getProperty("http.agent")
))。
您应该创建Interceptor
,它将添加服务器将接受的客户端标头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.