【问题标题】:Retrofit2.0.0 beta getting null response body ,response code is 400Retrofit2.0.0 beta 得到空响应体,响应码是 400
【发布时间】:2016-01-05 03:21:06
【问题描述】:

我是 Retrofit 的新手。我尝试在我的项目中实施 Retrofit 2.0.0 测试版。为了注册用户,我尝试了 Retrofit。方法 POST 是,内容类型是 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"
}  

我的注册课程是

public class Register {
   public  String status;
   public String error_code;
}

【问题讨论】:

    标签: android web-services gson response retrofit


    【解决方案1】:

    您的后端似乎不支持默认的User-Agent 标头,需要特定的标头。如果您没有明确提供此标头,我认为 OkHttp 将添加默认的User-Agent,即okhttp/version(对此不确定,可能是System.getProperty("http.agent"))。

    您应该创建Interceptor,它将添加您的服务器将接受的客户端标头。

    【讨论】:

      猜你喜欢
      • 2017-10-09
      • 2016-06-06
      • 2017-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      相关资源
      最近更新 更多