基于http发送post请求获取token接口的工具类,返回的json格式字符串。
重点:只需要修改map中的参数值,和tokenUrl就行
@Component
/**
*发送get/post请求接口
*/
public class SendRequestUtil {
//导入日志
private static final Logger log = LoggerFactory.getLogger(SendRequestUtil.class);
/**
* @param RequestConfig 连接超时配置
*/
private static RequestConfig requestConfig;
static{
requestConfig = RequestConfig.custom()
// 设置连接超时时间(单位毫秒)
.setConnectTimeout(40000)
// 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(30000)
// sock读写超时时间
.setSocketTimeout(20000)
// 设置是否允许重定向
.setRedirectsEnabled(true).build();
}
/**
* @return Post请求接口 响应Token信息
*/
public String sendPost() {
//请求参数Key/value 放入map集合
Map<String, String> tokenParam = new HashMap<>();
tokenParam.put(usernameKey,usernameVal);
tokenParam.put(passwordKey,passwordVal);
tokenParam.put(clientIdKey,clientIdVal);
tokenParam.put(clientSecretKey,clientSecretVal);
tokenParam.put(grantTypeKey,grantTypeVal);
// 打印参数日志
// for(String key:tokenParam.keySet()){
// log.info(("key--"+key+" | "+"Value--"+tokenParam.get(key)));
// }
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String result = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(tokenUrl);
// 创建参数列表
if (tokenParam != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : tokenParam.keySet()) {
paramList.add(new BasicNameValuePair(key, tokenParam.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
httpPost.setConfig(requestConfig);
}
// 执行http请求
response = httpClient.execute(httpPost);
result = EntityUtils.toString(response.getEntity(), "utf-8");
//将json转换对象存入responseToKens实体类方便调用,实体类是接口响应过来的参数写的
responseTokens = JSON.parseObject(result, ResponseToken.class);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
//类路径
import com.fasterxml.jackson.annotation.JsonProperty;
public class ResponseToken {
//@JsonProperty(value="access_token")作用于序列化属性名为另外一个名称
@JsonProperty(value="access_token")
private String accessToken;
@JsonProperty(value="expires_in")
private int expiresIn;
@JsonProperty(value="token_type")
private String tokenType;
@JsonProperty(value="refresh_token")
private String refreshToken;
private String scope;
//Get/Set方法
}