企业微信文档
企业微信开发者中心关于群机器人文档
图片推送接口:
核心代码
发送网络图片到群聊核心代码
/**
* 发送指定网络图片到群聊
* @param webHookUrl 群聊机器人
* @param sendImgUrl 网络图片地址
*/
public static void sendNetworkImgUrl(String webHookUrl, String sendImgUrl) {
InputStream in;
byte[] byteData = null;
try {
//获取流
//发送请求并且设置10秒超时时间
HttpResponse execute = HttpUtil.createGet(sendImgUrl).timeout(10000).execute();
in = execute.bodyStream();
byteData = new byte[in.available()];
in.read(byteData);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
String base64Str = Base64.getEncoder().encodeToString(byteData);
String md5Str = MD5.create().digestHex(byteData);
JSONObject eventTraceInput = JSONUtil.createObj();
eventTraceInput.put("msgtype", "image");
Map imageMap = new HashMap();
imageMap.put("base64", base64Str);
imageMap.put("md5", md5Str);
eventTraceInput.put("image", imageMap);
String body = HttpRequest.post(webHookUrl)
.header("Content-Type", "application/json")
.body(eventTraceInput.toString())//表单内容
.timeout(3000)//超时,毫秒
.execute()
.body();
JSONObject jsonObject = JSONUtil.parseObj(body);
if (!"ok".equals(jsonObject.getStr("errmsg"))){
System.out.println("发送失败,错误信息 >>>"+jsonObject.getStr("errmsg"));
}
}
演示
百度图片:
sendNetworkImgUrl("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=自己群的webHook"
,"https://img1.baidu.com/it/u=1960110688,1786190632&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281");