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