0

I wrote a web api in C # to authenticate, using postman sent the parameters and returns the token correctly, I will leave the parameters at the end of the post for testing, and searched for a lot of examples to bring parameters in JSON from a web api always me Send back the code 400 Bad request, I just want to connect from Java using the user and the password for the server to return the generated token for that login I used many codes and even nothing, this is the token I managed to generate using the postman But from Java only managed to generate 400 bad request.

I'm trying to authenticate to use it in an Android app

{
  "access_token": "vqWD9rZA2y8ydDxs8uT2L8pWQwjaMURaAcvuytdtq58zCzJS4OcbDJRw8lJQc7YbJ272cmzyhyPA7Ws_2dVH8ywmtwQRscVhZl-AgoLY61vZUDLJ6McJL7L_3zDrO-X5XfAV1DVBgkX8yPWwgVRSfhl17qG5zjuV8duVUBN8j7OvdU_FsTXePfBsamGMaBxzO6_oZjoJ1qPBAoy1AzfXhD4Dvm5Kwk_pJtL9MvfxSNkYKz0WSDNY1C0sm0-O3ml0A-1dr6F-jIiXxSyu90Jb2HHvS16L7mF6vPvvE3tElLV3a509XHRm2LbDTZOdGEHFrNl",
  "token_type": "bearer",
  "expires_in": 86399
}
url token: http://pedidostf.azurewebsites.net/token  
username : admin  
password : admin  
grant_type : password

This would be the last method I'm using for the connection

private class POST extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        //     InputStream inputStream = null;
        String cliente = params[0];
        String clave = params[1];
        String json = "";
        try {

            OkHttpClient client = new OkHttpClient();
            Request.Builder builder = new Request.Builder();
            builder.url(AppConfig.URL_TOKEN);
            builder.addHeader("Content-Type", "application/x-www-form-urlencoded");
            builder.addHeader("Accept", "application/json");

            FormBody.Builder parameters = new FormBody.Builder();
            parameters.add("grant_type", "password");
            parameters.add("username", cliente);
            parameters.add("password", clave);
            builder.post(parameters.build());

            Response response = client.newCall(builder.build()).execute();
            if (response.isSuccessful()) {
                 json = response.body().string();
                System.out.println("CONTENIDO::  " + json);

            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error: " + e);
        }



    return json;
}

I got of here

Get OAuth Token from Web API to android

Community
  • 1
  • 1
joe06
  • 418
  • 4
  • 17

1 Answers1

1

seems like you are doing GET request instead of POST request. when running on postman your snippet using GET request - it returns the same error, so I guess that's the problem.

follow this example how to use OkHttp to do POST request:

How to add parameters to api (http post) using okhttp library in Android

Community
  • 1
  • 1
Tal Kanel
  • 10,475
  • 10
  • 60
  • 98