@Component
@Slf4j
public class HttpUtils {
public static final String GET = "get";
public static final String POST = "post";
private HttpUtils() {
}
private HttpUtils(RestTemplate restTemplate) {
HttpUtils.restTemplate = restTemplate;
}
private static RestTemplate restTemplate;
//region HTTP GET 请求
/**
* HTTP GET 请求
*
* @param url 请求URL
* @param params 请求参数
* @return ReturnValue
*/
public static String get(String url, String params) {
Map<String,Object> map = JSONObject.parseObject(params, Map.class);
RestTemplate restTemplate = new RestTemplate();
if (map != null) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, Object> mapping : map.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(mapping.getKey());
sb.append("=");
sb.append(mapping.getValue());
}
if (url.indexOf("?") > 0) {
url += ("&" + sb.toString());
} else {
url += ("?" + sb.toString());
}
}
ResponseEntity<String> result;
try {
result = restTemplate.getForEntity(URI.create(url), String.class);
} catch (Exception ex) {
return ex.getMessage();
}
return result.getBody();
}
//endregion
public static <T> ResponseEntity<T> postByJson(String url, String params, Class<T> responseType) {
//设置Http的Header
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//设置访问的Entity
HttpEntity<String> entity = new HttpEntity<>(params, headers);
return restTemplate.exchange(url, HttpMethod.POST, entity, responseType);
}
public static String post(String url,String params,String contentType) throws Exception{
Map<String,Object> map = JSONObject.parseObject(params, Map.class);
try {
PostMethod postMethod = null;
postMethod = new PostMethod(url) ;
if (Objects.equals(MediaType.APPLICATION_FORM_URLENCODED_VALUE,contentType)){
postMethod.setRequestHeader("Content-Type", contentType); ;
//参数设置,需要注意的就是里边不能传NULL,要传空字符串
postMethod.setRequestBody(hashMapToNameValuePairList(map));
}else if (Objects.equals(MediaType.APPLICATION_JSON_UTF8_VALUE,contentType)){
RequestEntity re = new StringRequestEntity(params,MediaType.APPLICATION_JSON_VALUE,"UTF-8");
postMethod.setRequestEntity(re);
postMethod.setRequestHeader("Content-Type",MediaType.APPLICATION_JSON_VALUE);
//默认的重试策略
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
//设置超时时间
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 50000);
}
HttpClient httpClient = new HttpClient();
// 执行POST方法
httpClient.executeMethod(postMethod);
return postMethod.getResponseBodyAsString();
} catch (Exception e) {
log.error("请求异常"+e.getMessage(),e);
throw new RuntimeException(e.getMessage());
}
}
public static NameValuePair[] hashMapToNameValuePairList(Map<String,Object> map) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
String value = String.valueOf(entry.getValue());
list.add(new NameValuePair(key, value == null?"":value));
}
return list.toArray(new NameValuePair[0]);
}
/**
* 拼接url参数
* @return 格式: ?a=b&b=c
*/
public static String appendUrlParams(Map<String,Object> params){
StringBuffer sb = new StringBuffer();
sb.append("?");
for (Map.Entry<String,Object> mapping : params.entrySet()) {
if (sb.length() > 0) {
sb.append("&" + mapping.getKey() + "=" + mapping.getValue());
} else {
sb.append(mapping.getKey() + "=" + mapping.getValue());
}
}
return sb.toString();
}
}
调用示例:
@GetMapping("/QyWeiXin")
public String getAccessToken() throws Exception {
Map<String, String> dto = new HashMap<>();
//开发者的corpid
dto.put("corpid", corpid);
//应用密匙微信公众平台可找到
dto.put("corpsecret", corpsecret);
String params = JSONObject.toJSONString(dto);
// 发送Get请求
String s = HttpUtils.get(ACCESS_TOKER_URL, params);
Object o = JSONObject.toJSON(s);
JSONObject jsonObject = JSON.parseObject(s);
if (!jsonObject.get("errcode").equals(0)) {
throw new Exception("获取企业微信token失败,错误信息:" + s);
}
String accessToken = jsonObject.getString("access_token");
log.info("获取企业微信的token:"+accessToken);
return accessToken;
}