HTTP request works via POSTMAN but does NOT work via android app

Asked

Viewed 989 times

-1

I have an API for an android app that worked for a while. Used Laravel 5.3 on the server side and upgraded to 6.0.

By android application, I have returned the error "400 - Bad Request", but via Postman or Advanced REST Client the request works normally (with the same parameters).

Other systems are also working.

I am using: Java Android Retrofit 2 Okhttp GSON

Android app

interface Loginservice

@Headers({
        "Content-Type: application/json",
        "Accept: application/json"
})
@POST(Constants.API_LOGIN)
Call<Login> login(@Body Credentials credential);

Credentials

public class Credentials {

    // Atributos
    private String email;
    private String password;

    // GETs e SETs
    // Email
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    // Password
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    // Metodos
    @NonNull
    @Override
    public String toString() {
        return "{\"email\":\"" + getEmail() + "\", \"password\":\"" + getPassword() + "\"}";
    }

}

Login


//        JsonObject json = new JsonObject();
//        json.addProperty("email", AUTH_USER);
//        json.addProperty("password", AUTH_PASS);
        Credentials credential = new Credentials();
        credential.setEmail(AUTH_USER);
        credential.setPassword(AUTH_PASS);

        Call<Login> call = new RetrofitConfig().getLoginService().login(credential);
        call.enqueue(new Callback<Login>() {
            @Override
            public void onResponse(@NonNull Call<Login> call, @NonNull Response<Login> response) {
                Login login = response.body();
                Log.d(TAG, "RESPONSE: " + response.message());
                String msg = "Autenticado com sucesso.";
            }

            @Override
            public void onFailure(@NonNull Call<Login> call, @NonNull Throwable t) {
                Log.e(TAG, "Error: " + t.getMessage(), t);
                Toast.makeText(context, "Erro ao autenticar com servidor", Toast.LENGTH_SHORT).show();
                call.cancel();
            }

        });

POST Request

D/OkHttp: --> POST https://inoprime.com.br/api/login/
D/OkHttp: Content-Type: application/json
    Accept: application/json
    Content-Length: 61
D/OkHttp: {"email":"EMAIL","password":"****"}
    --> END POST (60-byte body)

Response

D/OkHttp: <-- 400 https://inoprime.com.br/api/login/ (2130ms)
    server: awselb/2.0
    date: Wed, 15 Jan 2020 14:36:31 GMT
    content-type: text/html
    content-length: 138
D/OkHttp: <html>
    <head><title>400 Bad Request</title></head>
    <body bgcolor="white">
    <center><h1>400 Bad Request</h1></center>
    </body>
    </html>
    <-- END HTTP (138-byte body)

Same request by Advanced REST Client

Request

Accept: application/json
Content-Type: application/json
cookie: COOKIE
content-length: 61
POST https://inoprime.com.br/api/login/ HTTP/1.1
Host: HOST
Accept: application/json
Content-Type: application/json
cookie: COOKIE
content-length: 61

 {"email":"EMAIL","password":"***"}

Response

> 200 OK

{
"token": "TOKEN"
}

Data from the ARC Preenchimento dos dados da requisição no ARC

Return of the ARC inserir a descrição da imagem aqui

ARC LOG inserir a descrição da imagem aqui

Someone can help me?

  • You set the Content-Length at 61: "Content-Length: 61" -- This does not seem correct, who has to inform the content-length is own lib, checking the requested payload and not you, unless you really know what you did... But usually "bad request" (400) is bad training on something in payload or headers. And I believe that your "log" done in the "Advanced REST Client" is "false", I mean, does not make sense the "verb" of HTTP (POST /api/login/ HTTP/1.1) be in the middle, it is the first thing to be sent by the server back...

  • ...off it has a spacing on the HTTP request before the {"email". There are many things there that you may have typed wrong when posting the question, or that you are actually doing wrong in your codes.

  • The ARC Content-length was generated alone... I came to copy and paste in the android header for test purposes... but gave the same result. In ARC I set the parameters by filling in the program’s "form"... and copied the "summary" q it does in the request to make it easy to create the question... In the case of /api/login, stackoverflow has indicated me the change by deleting the full host

  • I placed ARC prints to illustrate

  • I get it, you at copying time mixed everything up and scrambled everything in the answer you wrote here, so the rest is "right".... This part you write @Headers({&#xA; "Content-Type: application/json",&#xA; "Accept: application/json",&#xA; "Content-Length: 61"&#xA;})? Or is it "generated" too?

  • Can I make a suggestion? Creates a class that gets your email and its password and passes this Class in the @Body instead of JsonObject , Take this test and tell me what happened .

  • @Guilhermenascimento that part I q wrote msm... in the beginning, was without the Content-length, and gave the msm response... I put to look like the ARC msm...

  • @Ricardolucas I’ll try here

  • I removed Content-Length: 61 and made a credential class and passed as parameter as @Ricardolucas suggested. I got the same answer

  • I may be quite mistaken but it seems to me that by the APP you are giving direct post on the route: https://API The correct would not be on the route https://API/login ?

  • What is the value of Constants.API_LOGIN?

  • API_LOGIN = login/ API_HOST = https://inoprime.com.br/api/

Show 7 more comments

2 answers

1

I found the solution!

I inserted header Authorization in the Retrofit settings and it was working perfect. When upgrading Laravel to version 6.0, when inserting the Authorization empty (this api/login was to generate this token) returned the error 400 - Bad Request.

I just did an if to remove the Authorization when there is no token and now it is perfect! the/

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.level(HttpLoggingInterceptor.Level.BODY);

OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor)
        .addInterceptor(chain -> {
            Request request;
            if (LoginManager.getToken().length() > 5) {
                request = chain.request().newBuilder()
                        .header("Authorization", LoginManager.getToken())
                        .build();
            } else {
                request = chain.request().newBuilder().build();
            }
            return chain.proceed(request);
        })

-1

Here I am using HttpURLConnection, passing my fields to:

String campos = URLEncoder.encode("campo1", "UTF-8") + "=" + URLEncoder.encode(valor_campo1, "UTF-8");
bufferedWriter.write(campos);

That way it works here.

  • As I said, via ARC or other means works well... this app is a one-client solution (up to large)... and after the Laravel update, this request using Retrofit 2 stopped working... Changing the entire app would not be very feasible

Browser other questions tagged

You are not signed in. Login or sign up in order to post.