创建一个util类
public static JSONObject doPost(String url , Map<String,Object> paramMap , Map<String,String> headerMap){
log.info("dopost url = " + url);
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
JSONObject jsonObject = null;
String result = null;
//创建http实例
httpClient = HttpClients.createDefault();
//创建httpPost远程实例
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)//设置连接主机超时时间
.setConnectionRequestTimeout(35000)//连接请求超时时间
.setSocketTimeout(60000)//读取数据超时时间
.build();
httpPost.setConfig(requestConfig);
if(headerMap == null){
httpPost.addHeader("Content-Type","application/x-www-form-urlencoded");
}else{
for(String key : headerMap.keySet()){
httpPost.addHeader(key,headerMap.get(key));
}
}
if(paramMap.size()>0 && paramMap != null){
List list = new ArrayList<>();
Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
while(iterator.hasNext()){
Map.Entry<String, Object> next = iterator.next();
list.add(new BasicNameValuePair(next.getKey(),next.getValue().toString()));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
}
}
try {
httpResponse = httpClient.execute(httpPost);
result = EntityUtils.toString(httpResponse.getEntity());
jsonObject = JSONObject.parseObject(result);
} catch (IOException e) {
log.error(e.getMessage(), e);
}finally {
if(httpResponse != null){
try {
httpResponse.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
if(httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return jsonObject;
}
上述代码中url
是Access Token
的url
,paramMap
是获取token需要的参数。
例:
paramMap.put("grant_type","client_credentials");
paramMap.put("client_id","your client_id");
paramMap.put("client_secret","your client_secret");
paramMap.put("scope","");
将上述参数传入后,得到一个jsonObject
类型的返回值
使用jsonObject.get("access_token").toString()
获取token
创建一个map里面传入Content-Type
,Authorization
如下:
Map headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer "+token);
最后调用HttpUtils提供的post方法,里面参数为连接地址url,传入的参数及上面的map
HttpUtils.post(“target url”, JSON.toJSONString(param) ,headers);
返回值为一个String字符串。
连接完成!