HttpClientTool 进行basic auth认证并携带Bearer Token

HttpClientTool 进行basic auth认证并携带Bearer Token

对接方OAuth2.0协议

首先根据对接文档,尝试用postman访问

在这里插入图片描述
在这里插入图片描述
获取成功

{
    "result": {
        "access_token": "2d6ed2af-b988-40ea-937f-a0b22b7c6db4",
        "token_type": "bearer",
        "refresh_token": "007f75db-202e-4000-bbef-a6c0ed78ceb1",
        "expires_in": 508337,
        "scope": "all"
    },
    "code": "200",
    "msg": ""
}

使用httpClientTool

   <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
      <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.4.1</version>
        </dependency>
    public CloseableHttpResponse getToken() {
        CloseableHttpResponse response = null;
        try {
            CloseableHttpClient createDefault = HttpClients.custom()
                    .build();
            JSONObject params = new JSONObject();
            params.set("grant_type", "password");
            params.set("username", "xx");
            params.set("password", "xx");

            HttpPost post = new HttpPost(PRE + TOKEN_URL);
            StringEntity entity = new StringEntity(params.toString(), "UTF-8");
            entity.setContentEncoding("UTF-8");
            post.addHeader(BasicScheme.authenticate(
                    new UsernamePasswordCredentials(USERNAME, PASSWORD),
                    "UTF-8", false));
            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("grant_type", new StringBody(grant_type, ContentType.TEXT_PLAIN))
                    .addPart("username", new StringBody(USERNAME_BODY, ContentType.TEXT_PLAIN))
                    .addPart("password", new StringBody(PASSWORD_TYPE, ContentType.TEXT_PLAIN)).build();
            post.setEntity(reqEntity);

            response = createDefault.execute(post);
            return response;
        } catch (Exception e) {
            log.error("获取xxtoken报错:{}", e);
        }
        return response;
    }

后续携带token的工具类

  public static String doPostAuthoriZationForJson(String url, String json, String token)
            throws IOException {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.addHeader("Accept", "application/json");
        //温州的
        if (!StringUtils.isEmpty(token)) {
            httpPost.addHeader("Authorization", "Bearer " + token);
        }
        CloseableHttpResponse response = null;
        try {
            if (!"".equals(json)) {
                // 这里是关键,后面要跟上字符集格式
                StringEntity params = new StringEntity(json, "utf-8");
                params.setContentEncoding("utf-8");
                // 发送json数据需要设置contentType
                params.setContentType("application/json");
                httpPost.setEntity(params);
            }
            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                log.error("发起的请求{}",httpPost);
                log.error("报错说明{}",response);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            return result;
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return null;

    }
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值