使用齐射进行WebAPI调用 [英] WebAPI call using volley

查看:79
本文介绍了使用齐射进行WebAPI调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用齐射字符串请求从服务器获取访问令牌。我也尝试过制作JsonObjectRequest。两者都在下面。

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", "support@xxx.com");
                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", "support@xxx.com");
        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

我写服务器端代码的同事询问如何将以下Angular代码(他的可与API一起使用的代码)转换为Android。

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.

任何人都可以帮忙吗?

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 });
    }


推荐答案

问题是几个

我将 params.put( resource, window.location.origin);替换为 params.put( resource, < a href = https://lw.xxx.co.uk rel = nofollow noreferrer> https://lw.xxx.co.uk );

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

此外,我发现Volley忽略了getHeaders重写,因此我注释掉了该方法,并使用以下方法设置了标题。

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

这篇关于使用齐射进行WebAPI调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆