加密工具类(JAVA 带demo)
<pre><code>public class SignUtils
{
//编码格式
private static String inputCharset = &quot;utf-8&quot;;
/**
* 生成MD5 32位小写加密
* @param prestr 需要签名的字符串
* @param appsecret
* @return
*/
private static String Sign(String prestr, String appsecret){
StringBuffer buf = new StringBuffer(32);
String str = prestr + appsecret;
try {
MessageDigest md = MessageDigest.getInstance(&quot;MD5&quot;);
md.update(str.getBytes());
byte b[] = md.digest();
int i;
for (int offset = 0; offset &lt; b.length; offset++) {
i = b[offset];
if (i &lt; 0)
i += 256;
if (i &lt; 16)
buf.append(&quot;0&quot;);
buf.append(Integer.toHexString(i));
}
str = buf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
/**
* 生成请求时的签名
* @param sPara 参与签名参数,包含header和body中的参数,其中不能包含sign和appsecret
* @param appsecret 秘钥和appid对应,由脉餐宝提供
* @return md5 32位小写签名
*/
public static String BuildSign(Map&lt;String, String&gt; sPara, String appsecret){
//把数组所有元素,按照“参数=参数值”的模式用“&amp;”字符拼接成字符串
String prestr = CreateLinkString(sortMapByKey(sPara));
//把最终的字符串签名,获得签名结果
String mysign = Sign(prestr, appsecret);
return mysign;
}
/// &lt;summary&gt;
/// 把数组所有元素,按照“参数=参数值”的模式用“&amp;”字符拼接成字符串
/// &lt;/summary&gt;
/// &lt;param name=&quot;dicArray&quot;&gt;需要拼接的数组&lt;/param&gt;
/// &lt;returns&gt;拼接完成以后的字符串&lt;/returns&gt;
private static String CreateLinkString(Map&lt;String, String&gt; dicArray){
StringBuilder prestr = new StringBuilder();
//C#代码
// foreach (Map&lt;String, String&gt; temp in dicArray)
// {
// prestr.Append(temp.Key + &quot;=&quot; + temp.Value + &quot;&amp;&quot;);
// }
//
// //去掉最後一個&amp;字符
// int nLen = prestr.Length;
// prestr.Remove(nLen - 1, 1);
//
// return prestr.ToString();
//JAVA
for(Map.Entry&lt;String,String&gt; entry:dicArray.entrySet()){
prestr.append(entry.getKey() + &quot;=&quot; + entry.getValue() + &quot;&amp;&quot;);
}
//去掉最後一個&amp;字符
String str = prestr.substring(0,prestr.length() -1);
return str;
}
/**
* 使用 Map按key进行排序
* @param map
* @return
*/
private static Map&lt;String, String&gt; sortMapByKey(Map&lt;String, String&gt; map) {
if (map == null || map.isEmpty()) {
return null;
}
Map&lt;String, String&gt; sortMap = new TreeMap&lt;&gt;(new Comparator&lt;String&gt;() {
public int compare(String obj1, String obj2) {
return obj1.compareTo(obj2);//升序排序
}
});
sortMap.putAll(map);
return sortMap;
}
public static void main(String[] args) throws UnsupportedEncodingException {
//unix时间戳,精确到秒
Long ticks = System.currentTimeMillis() / 1000;
//请求参数,请向脉餐宝工作人员获取
String apiUrl = &quot;https://api.maicanbao.com/Out/Member/SycnPersonFiles&quot;;
String appid=&quot;9c145a40-8c3a-48c4-8ab3-cbf8c937320b&quot;;
String appsecret = &quot;123654789&quot;;
String appsecretcode = &quot;99&quot;;
//放入请求头中
Map&lt;String, String&gt; headerMap = new HashMap&lt;&gt;();
headerMap.put(&quot;ticks&quot;,ticks.toString());
headerMap.put(&quot;appid&quot;, appid);
headerMap.put(&quot;appsecretcode&quot;,appsecretcode);
//请求参数:POST请求放入BODY中
Map&lt;String, Object&gt; params = new HashMap&lt;&gt;();
User user = new User();
user.setNumbercode(&quot;01002&quot;);
user.setName(&quot;测试&quot;);
user.setMemberId(0);
user.setStatus(0);
user.setFirm(&quot;&quot;);
user.setDepartment(&quot;&quot;);
user.setIdcard(&quot;&quot;);
user.setPhone(&quot;&quot;);
// badyData.delete = delList;
List&lt;User&gt; userList = new ArrayList&lt;&gt;();
userList.add(user);
List&lt;String&gt; delList = new ArrayList&lt;&gt;();
//此处value不能放序列化后的,应该直接存入对象
params.put(&quot;update&quot;,userList);
params.put(&quot;delete&quot;,delList);
HashMap&lt;String,String&gt; preSignMap=new HashMap&lt;&gt;();
preSignMap.putAll(headerMap);
// preSignMap.put(badyData);
for(Map.Entry&lt;String,Object&gt; entry:params.entrySet()){
//URLENCODE时将+号转换成%20,生成大写的%+符号
//value应该进行json序列化后再进行urlencoder
preSignMap.put(entry.getKey(),java.net.URLEncoder.encode(JSON.toJSONString(entry.getValue()),&quot;utf-8&quot;).replaceAll(&quot;\\+&quot;, &quot;%20&quot;));
}
//计算sign
String newSign = BuildSign(preSignMap,appsecret);
headerMap.put(&quot;sign&quot;,newSign);
//请求
String resultStr=doPost(apiUrl,params,headerMap);
JSONObject result = JSON.parseObject(resultStr);
System.out.println(result.toString());
}
//////////////////////////httpClient Post方法/////////////////
private static final int SocketTimeout = 60000;
private static final int ConnectTimeout = 60000;
private static final int ConnectionRequestTimeout = 60000;
private static RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(SocketTimeout)
.setConnectTimeout(ConnectTimeout)
.setConnectionRequestTimeout(ConnectionRequestTimeout)
.setStaleConnectionCheckEnabled(true)
.build();
/**
* 发送 POST 请求(HTTP),带输入数据 带header
*
* @param paramMap 请求Body中参数Map,值不需要进行UrlEncode
* @param headerMap 请求头header Map
* @return
*/
public static String doPost(String apiUrl, Map&lt;String, Object&gt; paramMap,Map&lt;String, String&gt; headerMap) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
httpPost.addHeader(&quot;Content-type&quot;,&quot;application/json; charset=utf-8&quot;);
httpPost.setHeader(&quot;Accept&quot;, &quot;application/json&quot;);
for (Map.Entry&lt;String, String&gt; header : headerMap.entrySet()) {
httpPost.setHeader(header.getKey(),header.getValue());
}
try {
httpPost.setConfig(defaultRequestConfig);
httpPost.setEntity(new StringEntity(JSON.toJSONString(paramMap),&quot;UTF-8&quot;));
response = httpClient.execute(httpPost);
// System.out.println(response.toString());
HttpEntity entity = response.getEntity();
httpStr = EntityUtils.toString(entity, &quot;UTF-8&quot;);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
}</code></pre>