记录下自己,话不多说,直接上代码(转发请注明出处):
https://blog.csdn.net/kangzhuang521/article/details/94620044
/**
* http请求工具
* @author kangzhuang
* @Date 20190701
*/
public class HttpSendUtils {
/**
* 引入日志
*/
private static final Logger logger = LoggerFactory.getLogger(HttpSendUtils.class);
private static final String CHARSET_UTF8 = "utf-8";
private static final String SEPEATER = "_";
/**
* post请求,json方式请求,默认编码utf8
*
* @param url
* @param params
* @return
*/
public static String doPostJson(String url, Map params) {
return sendPostRequest(url, params, CHARSET_UTF8);
}
/**
* post请求,json方式请求,可自定义编码格式
*
* @param url 请求地址
* @param params 需要穿的参数
* @param charset 设置字符集
* @return 响应json报文数据
*/
public static String sendPostRequest(String url, Map<String,String> params, String charset) {
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try {
httpClient = HttpClientBuilder.create().build();
httpPost = new HttpPost(url);
// 设置参数
JSONObject jsonParam = new JSONObject();
if (params != null && params.size() > 0) {
// 将参数转换为json格式
Iterator iterator = params.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry elem = (Map.Entry) iterator.next();
jsonParam.put(String.valueOf(elem.getKey()), elem.getValue());
}
}
if (jsonParam.size() > 0) {
StringEntity entity = new StringEntity(jsonParam.toString(), charset);
// 这里务必设置为application/json;charset=UTF-8
entity.setContentType("application/json;charset=UTF-8");
entity.setContentEncoding(charset);
// 设置参数
httpPost.setEntity(entity);
}else{
logger.error("sendPostRequest参数jsonParam.toString()参数为空!");
}
// 发送请求
HttpResponse response = httpClient.execute(httpPost);
// 返回响应
if (response == null) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, charset);
}
} catch (Exception e) {
logger.error(" sendPostRequest 出现异常:"+e);
}
return result;
}
/**
* 加密
*
* @param map
* @return
*/
public static String getSign(Map<String, String> map) {
String accessKeyId = (String) map.get("accessKeyId");
String timestamp = (String)map.get("timestamp");
String saltStr = (String) map.get("saltStr");
// 根据accessKeyId查询对应的accessKeySecret
String accessKeySecret = (String)map.get("accessKeySecret");
// 生成签名
StringBuilder builder = new StringBuilder();
builder.append(accessKeyId).append( "_").append(timestamp).append( "_")
.append(saltStr).append( "_").append(accessKeySecret).append( "_").append(accessKeyId);
logger.error("getSign 返回结果builder.toString():{}"+builder.toString());
MD5Util md5 = new MD5Util();
//加密
String targetSign = md5.toDigest(builder.toString());
return targetSign;
}
/**
* 主方法
*
* @param args
*/
public static void main(String[] args) {
// 请求的url地址
String url = "";
Map<String, String> map = new HashMap<String, String>();
// 提供的accessKeyId
map.put("accessKeyId", "y666");
// 随机生成32位盐值
map.put("saltStr", "33333");
// 当前时间的时间戳
map.put("timestamp",String.valueOf(new Date().getTime()));
// 根据accessKeyId查询对应的accessKeySecret
map.put("accessKeySecret","66666");
map.put("sign", getSign(map));
for(Map.Entry<String, String> entry : map.entrySet()) {
if (StringUtil.isEmpty(entry.getValue())) {
logger.error("请求参数有空值:"+entry.getKey());
// return entry.getKey()+"为空";
}
}
String result = HttpSendUtils.sendPostRequest(url, map, CHARSET_UTF8);
JSONObject jsonObject = JSONObject.parseObject(result);
jsonObject.getString("code");
}
}
----------------------------------------------------------------------------------------
/**
* md5 加密工具
* @author 康壮
* @date 20190701
*/
public class MD5Util {
/**
* 引入日志
*/
private static final Logger logger = LoggerFactory.getLogger(MD5Util.class);
/**
* 简单md5加密
* @param originalText 加密前的文本信息
* @return
*/
public static String toDigest(String originalText) {
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try {
byte[] strTemp = originalText.getBytes(StandardCharsets.UTF_8);
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char[] str = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 15];
str[k++] = hexDigits[byte0 & 15];
}
return new String(str);
} catch (Exception e) {
logger.error("MD5Util toDigest error:{}"+e);
return null;
}
}
}
------------------------------------------------------------------------------------------------------
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
</dependency>