使用java发送钉钉消息

钉钉设置:
1、创建群聊

2、群聊设置自定义机器人:

3、获取webhook地址

4、写代码:

public class MessageService {

	public static String url = "https://oapi.dingtalk.com/robot/send?access_token=****";
	
	public static String keyWords = "监控信息:";
	
	public static String sendMessage(String json) {
		try {
			HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
			httpRequestFactory.setConnectionRequestTimeout(500);
			httpRequestFactory.setConnectTimeout(500);
			httpRequestFactory.setReadTimeout(500);
			RestTemplate template = new RestTemplate(httpRequestFactory);
			//ClientHttpRequestFactory clientFactory = new HttpComponentsClientHttpRequestFactory();
			//template.setRequestFactory(clientFactory);
			URI uri = UriComponentsBuilder.fromUriString(url) //
					.build().encode().toUri();
			HttpHeaders requestHeaders = new HttpHeaders();
			requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
			requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON_UTF8));
			@SuppressWarnings({ "rawtypes", "unchecked" })
			HttpEntity<String> requestEntity = new HttpEntity(json,requestHeaders);
			ResponseEntity<String> responseEntity = template.exchange(uri, HttpMethod.POST, requestEntity,
					String.class);
			System.out.println(responseEntity.getBody());
			return responseEntity.getBody();
		} catch (Exception e) {
			//do noting
		}
		return null;
	}
	
	public static String sendTextMsg(String text) {
		JSONObject json = new JSONObject();
		json.put("msgtype", "text");
		Map<String,String> map = new HashMap<>();
		map.put("content", keyWords + text);
		json.put("text",map);
		return sendMessage(json.toString());
	}
	
	public static String sendLinkMsg(String title,String text,String picUrl,String messageUrl) {
		JSONObject json = new JSONObject();
		json.put("msgtype", "link");
		Map<String,String> map = new HashMap<>();
		map.put("text", keyWords + text);
		map.put("title", title);
		map.put("picUrl", picUrl);
		map.put("messageUrl", messageUrl);
		json.put("link",map);
		return sendMessage(json.toString());
	}

	public static void main(String[] args) {
		sendTextMsg("测试");
	}

你可能感兴趣的:(Java生产环境,java,开发语言,后端)