I am new to Retrofit.I tried to implement Retrofit 2.0.0 beta in my project. To register a user i tried Retrofit. The METHOD POST is and Content Type is application/x-www-form-urlencoded
. I am getting response as 400 but response body is null
. I am attaching my code here.
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) {
}
});
I am getting response as
{
status: "failed"
error_code: "invalid_client"
}
and my Register class is
public class Register {
public String status;
public String error_code;
}
Your backend seems to does not support default User-Agent
header and requires specific one. If you do not provide this header explicitly, I think OkHttp will add default User-Agent
which is okhttp/version
(not sure about this, could be System.getProperty("http.agent")
).
You should create Interceptor
which will add the client header that your server will accept.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.