实现功能:艾特全体,根据手机号艾特具体某人
package com.bbs.freight;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class SendHttps {
/**
* 发送POST请求,参数是Map, contentType=x-www-form-urlencoded
*
* @param url
* @param mapParam
* @return
*/
public static String sendPostByMap(String url, Map<String, Object> mapParam) {
Map<String, String> headParam = new HashMap();
headParam.put("Content-type", "application/json;charset=UTF-8");
return sendPost(url, mapParam, headParam);
}
/**
* 向指定 URL 发送POST方法的请求
* 放在测试环境时中文乱码解决方法
*
* @param url 发送请求的 URL
* @param param 请求参数,
* @return 所代表远程资源的响应结果
*/
public static String doPost(String url, Map<String, Object> param, Map<String, String> headParam){
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Content-Type", "application/json; charset=utf-8");
StringEntity se = new StringEntity(JSON.toJSONString(param), "utf-8");
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String result = null;
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity());
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, Map<String, Object> param, Map<String, String> headParam) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection )realUrl.openConnection();
// 设置通用的请求属性 请求头
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Fiddler");
if (headParam != null) {
for (Entry<String, String> entry : headParam.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(JSON.toJSONString(param));
//out.write(string.getBytes()); //中文乱码问题可以改成witeBytes,这个我没有测试过,使用时可以自己测试下
//out.writeBytes(string);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException{
//机器人要是打开了签名,则需要签名计算,否则不需要此步骤
Long timestamp = System.currentTimeMillis();
String secret = "secret ";
String stringToSign = timestamp + "\n" + secret;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
System.out.println(sign);
// 钉钉的webhook,要是没勾选签名,请求链接则不需要“timestamp”与“sign”参数
String dingDingToken="webhook"
+ "×tamp=" + timestamp
+ "&sign="+ sign;
// 请求的JSON数据,这里我用map在工具类里转成json格式,要是填写关键字发送,content里需要包含关键字
Map<String,Object> json=new HashMap();
Map<String,Object> text=new HashMap();
Map<String,Object> at=new HashMap();
Map<String,List<String>> atMobiles = new HashMap();
List mob = new ArrayList<String>();
mob.add("122332322");//艾特人的手机号
json.put("msgtype","text");
text.put("content","test爱上九点半的我");
atMobiles.put("atMobiles", mob);//艾特人的手机号
at.put("isAtAll", false);//是否艾特所有人
at.put("atMobiles", mob);
json.put("text",text);
json.put("at",at);
// 发送post请求
String response = SendHttps.sendPostByMap(dingDingToken, json);
System.out.println("相应结果:"+response);
}
}
官方文档: