2015-10-07 55 views
0

我是新的Retrofit.I試圖在我的項目中實施Retrofit 2.0.0測試版。要註冊一個用戶,我試過Retrofit。方法POST是和內容類型是application/x-www-form-urlencoded。我得到的答覆是400,但答覆機構是null。我在這裏附上我的代碼。Retrofit2.0.0測試版獲得空響應主體,響應代碼爲400

public interface MyApiInterface { 
    @Headers("Content-Type: application/x-www-form-urlencoded") 
    @FormUrlEncoded 
    @POST("https://stackoverflow.com/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; 
} 

回答

0

後端似乎不支持默認User-Agent頭和需要特定的一個。如果你不明確提供這個頭,我認爲OkHttp會添加默認的User-Agent這是okhttp/version(不知道這個,可能是System.getProperty("http.agent"))。

您應該創建Interceptor這將添加您的服務器將接受的客戶端標頭。

+0

謝謝..你可以給我看一個例子嗎? – Divya