Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST x-www-form-urlencoded in retrofit

I have request with login to API

Call<TokenJSONModel> login(@Header("Authorization") CredentialsModel credentials, @Field("access_token") String authKey );

authKey is x-www-form-urlencoded

so i added @FormUrlEncoded before POST but still receive 400 Bad Request.

I double chcecked adres, args in debug are corect credentials with "Basic" prefix but authKey don't have access_token prefix.

In postman everything is ok i receive token and user.

I tried:

Call<TokenJSONModel> call = RetrofitClient.getInstance().getApi().login(credentials, "access_token:"+authKey));

but nothing changed.

On bad credentials or token i should receive 401 unauthorized, for good 201 Created.

Logs from api:

2019-06-04T19:17:06.796534+00:00 app[web.1]: POST /auth 400 0.477 ms - -
2019-06-04T19:17:07.068321+00:00 heroku[router]: at=info method=POST path="/auth" my_webserver.com request_id=5c4efe45-5d54-4fde-8420-d0fcb3338558 fwd="148.81.117.54" dyno=web.1 connect=1ms service=3ms status=400 bytes=188 protocol=https
2019-06-04T19:17:07.069147+00:00 app[web.1]: POST /auth 400 0.519 ms - -
2019-06-04T19:17:17.711709+00:00 app[web.1]: POST /auth 201 43.530 ms - 393
2019-06-04T19:17:17.713351+00:00 heroku[router]: at=info method=POST path="/auth" my_webserver.com request_id=3ff2fdea-c23b-40ef-8f62-acc410068007 fwd="148.81.117.54" dyno=web.1 connect=0ms service=45ms status=201 bytes=662 protocol=https

1st one is for android retrofit request, 2nd is from postman. I notice that android request is 3.5x smaller than requestfrom postman - why?

like image 325
Kamil Avatar asked Jun 04 '19 15:06

Kamil


1 Answers

Ok i found a solution. After i added

    @Headers({
            "Content-Type: application/x-www-form-urlencoded",
            "accept-encoding: gzip, deflate",
            "access_token: mtlNzTVmXP4IBSba3z4XXXX",
            "Authorization: Basic a2FtaWwua2ljaW5za2lAc3R1ZGVudC53YXQuZXXX"
    })
    @FormUrlEncoded
    @POST("/auth")

I noticed that everything works. Credential that i pass in my request was treated as a reference to object of CredentialsModel contains String when server wanted alone String. I fixed it by:

    @FormUrlEncoded
    @POST("/auth")
    Call<ResponseBody> login(@Header("Authorization") String credentials, @Field("access_token") String authKey );

and

Call<ResponseBody> call = RetrofitClient.getInstance().getApi().login(Credentials.basic(email, password),authKey);
like image 52
Kamil Avatar answered Sep 19 '22 23:09

Kamil