我是Retrofit的新手。我试图在我的项目中实现Retrofit 2.0.0 beta。要注册用户我试过Retrofit。 METHOD 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"
}
我的Register类是
public class Register {
public String status;
public String error_code;
}
答案 0 :(得分:0)
您的后端似乎不支持默认User-Agent
标头,并且需要特定的标头。如果您没有明确提供此标头,我认为OkHttp将添加User-Agent
的默认okhttp/version
(对此不确定,可能是System.getProperty("http.agent")
)。
您应该创建Interceptor
,这将添加您的服务器将接受的客户端标头。