Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebAPI call using volley

I'm trying to get access tokens from the server using a volley String request. I have tried making a JsonObjectRequest also. Both are below.

public void getAuthenticationTokens(Object param1, final CustomListener<String> listener)
    {

        //String url = prefixURL + "this/request/suffix";
        String url = "https://lw.xxx.co.uk/connect/token";


        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        // response
                        Log.e("Response", response);
                    }
                },


                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        Log.e("Error.Response", error.networkResponse.toString());
                    }
                }
        ) {



            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                params.put("Content-Type","application/x-www-form-urlencoded");
                //..add other headers
                return params;
            }

            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<String, String> ();
                params.put("scope", "openid email phone profile offline_access roles");
                params.put("resource", "window.location.origin");
                params.put("grant_type", "password");
                params.put("username", "[email protected]");
                params.put("password", "tempPxxx");


                return params;
            }

        };

        requestQueue.add(request);

.

public void getAuthenticationTokens(Object param1, final CustomListener<String> listener)
    {

        //String url = prefixURL + "this/request/suffix";
        String url = "https://lw.xxx.co.uk/connect/token";

Map<String, Object> jsonParams = new HashMap<>();

        jsonParams.put("scope", "openid email phone profile offline_access roles");
        jsonParams.put("resource", "window.location.origin");
        jsonParams.put("grant_type", "password");
        jsonParams.put("username", "[email protected]");
        jsonParams.put("password", "tempPxxx");

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(jsonParams),
                new Response.Listener<JSONObject>()
                {
                    @Override
                    public void onResponse(JSONObject response)
                    {
                        Log.d(TAG + ": ", "somePostRequest Response : " + response.toString());
                        if(null != response.toString())
                            listener.getResult(response);
                    }
                },

                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error)
                    {
                        if (null != error.networkResponse)
                        {

                            Log.e(TAG + ": ", "Error Response code: " + error.networkResponse.statusCode);



                            listener.getResult(null);
                        }
                    }
                }){
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                       // Map<String,String> params =  super.getHeaders();
                       // if(params==null)params = new HashMap<>();
                        Map<String,String> params = new HashMap<>();
                        params.put("Content-Type","application/x-www-form-urlencoded");
                        //..add other headers
                        return params;
                    }
        };



        requestQueue.add(request);

.

I get the following response from the server:

E/Volley: [31388] BasicNetwork.performRequest: Unexpected response code 400 for https://lw.xxx.co.uk/connect/token

.

My colleague who has written the server-side code has asked how to convert the following Angular code (his code that works with the API), to Android.

Can anyone help with this?

getLoginEndpoint(userName: string, password: string): Observable<Response> {

        let header = new Headers();
        header.append("Content-Type", "application/x-www-form-urlencoded");

        let searchParams = new URLSearchParams();
        searchParams.append('username', userName);
        searchParams.append('password', password);
        searchParams.append('grant_type', 'password');
        searchParams.append('scope', 'openid email phone profile offline_access roles');
        searchParams.append('resource', window.location.origin);

        let requestBody = searchParams.toString();

        return this.http.post(this.loginUrl, requestBody, { headers: header });
    }
like image 581
turtleboy Avatar asked Nov 10 '17 16:11

turtleboy


People also ask

What is API volley?

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available on GitHub. Volley offers the following benefits: Automatic scheduling of network requests. Multiple concurrent network connections.

Is volley a REST API?

Android Volley and Retrofit are the most used libraries for accessing the REST Web APIs today.


1 Answers

The problem was a couple of things.

I replaced "params.put("resource", "window.location.origin"); " with "params.put("resource", "https://lw.xxx.co.uk");"

Also, I found out that Volley ignore the getHeaders override, so I commented that method out and used the following to set the headers.

@Override
            public String getBodyContentType() {
                return "application/x-www-form-urlencoded";
            }

public void getAuthenticationTokens(Object param1, final String userName, final String password, final CustomListener<JSONObject> listener)
    {
        String url = "https://lw.xxx.co.uk/connect/token";
        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        // response
                        Log.e("Response", response);

                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        Log.e("Error.Response", error.networkResponse.toString());
                    }
                }
        ) {

           /* @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                params.put("Content-Type","application/x-www-form-urlencoded");
                //..add other headers
                return params;
            }*/
            @Override
            public String getBodyContentType() {
                return "application/x-www-form-urlencoded";
            }

            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<String, String> ();
                params.put("scope", "openid email phone profile offline_access roles");
                params.put("resource", "https://lw.xxx.co.uk");
                params.put("grant_type", "password");
                params.put("username", userName);
                params.put("password", password);
                return params;
            }


            @Override
            protected VolleyError parseNetworkError(VolleyError response) {
                try {

                    String json = new String(response.networkResponse.data, HttpHeaderParser.parseCharset(response.networkResponse.headers));
                    Log.e(TAG, "reponse error = " + json);
                }catch (Exception e){}
                return super.parseNetworkError(response);
            }
        };
        requestQueue.add(request);

    }//end of getAuthenticationTokens
like image 130
turtleboy Avatar answered Sep 28 '22 02:09

turtleboy