为 API 调用生成 Android 令牌

问题描述

我正在开发一个带有 API 调用的 Android 应用程序。对于 API 调用,我需要在调用 API 时提供有效的令牌。要生成此令牌,需要使用一些参数,例如大类型、范围等,并且主体应采用表单数据格式。 我已经尝试了以下代码,但大多数类在最新版本中已被弃用。我的应用仅从 26 开始支持

 public static Object getAccesstoken(String address,String grant_type,String client_Id,String client_Secret,String scope) throws Exception {

        JSONObject jObj = null;
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("grant_type",grant_type));
        params.add(new BasicNameValuePair("client_Id",client_Id));
        params.add(new BasicNameValuePair("client_Secret",client_Secret));
        params.add(new BasicNameValuePair("scope",scope));
        // Making HTTP request
        HttpResponse httpResponse = makeHTTPRequest(address,params);
        if (httpResponse != null) {
             int statusCode = httpResponse.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_BAD_REQUEST) {
                Log.d("Token",httpResponse.getStatusLine().toString());
                return httpResponse.getStatusLine().toString();
            }


        }

        return jObj;
    }

    private static HttpResponse makeHTTPRequest(String address,List<NameValuePair> params) {
        HttpClient httpClient = new HttpClient();
        HttpPost httpPost = new HttpPost(address);
        httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
        HttpResponse httpResponse = null;
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            httpResponse = httpClient.execute(httpPost);

        } catch (UnsupportedEncodingException e) {
            e.printstacktrace();
        } catch (ClientProtocolException e) {
            e.printstacktrace();
        } catch (IOException e) {
            e.printstacktrace();
        }
        return httpResponse;
    }

任何人,请提出更好的解决方案。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)