Java调用微信发送文本接口

本文介绍了一种通过Java实现的企业微信消息推送方法。具体包括获取access_token的过程及使用该token发送文本消息到指定用户的详细步骤。文章提供了完整的代码示例,涵盖了获取access_token的HTTP GET请求及发送消息的HTTP POST请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.utils.HttpsGet;

public class WechatSendMsg {
	
	public static final String WECHAT_MSG_CORP_ID = "wx77231802e9e4ea14";
	public static final String WECHAT_MSG_CORP_SECRET = "3irDewN7Hf4XqYnvg4gXO_n5Tf4pxA7tDqsUMfP6EZZKQLOb3dmMVsabwZ6AVaD2";
	public static final int WECHAT_MSG_AGINT = 3;
	
	private static String getAccessToken(String corpId, String corpSecret){
		try{
			String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpId+"&corpsecret="+corpSecret+"";
			HttpsGet hGet=new HttpsGet(url);
			
			JSONObject jo = JSON.parseObject(hGet.DoGet());
			return jo.getString("access_token");
		}catch(Exception e){
			e.printStackTrace();
		}
		return "";
	}
	
	public static String sendText(String msg,String toUsers){
		try{
			String access_token= getAccessToken(WECHAT_MSG_CORP_ID,WECHAT_MSG_CORP_SECRET);
			
			String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+access_token;
			JSONObject jo = new JSONObject();
			jo.put("touser", toUsers);
			jo.put("msgtype", "text");
			jo.put("agentid", WECHAT_MSG_AGINT);//应用ID
			
			/* "toparty": " PartyID1 | PartyID2 ", 部门id
			   "totag": " TagID1 | TagID2 ",标签id  */
			
			JSONObject jo_text = new JSONObject();
			jo_text.put("content", msg);
			
			jo.put("text",  jo_text);
			jo.put("safe", 0);
			
			/*System.out.println(access_token);
			System.out.println(JSON.toJSONString(jo));*/
			JSONObject rJo = JSON.parseObject(sendPost(url,JSON.toJSONString(jo)));
			System.out.println("微信接口返回值:"+rJo.getString("errcode"));
			return rJo.getString("errcode");
		}catch(Exception e){
			e.printStackTrace();
		}
		return "1";
	}
	
	/** 
     * 发送Postq请求
     * @param urlStr
     * @param param
     * @return
     */
	private static String sendPost(String urlStr, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            //设置参数
            httpConn.setDoOutput(true);   //需要输出
            httpConn.setDoInput(true);   //需要输入
            httpConn.setRequestMethod("POST");   //设置POST方式连接
            //设置请求属性
            httpConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            //建立输入流,向指向的URL传入参数
            DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
            dos.write(param.getBytes("utf-8"));
            dos.flush();
            dos.close();
            //获得响应状态
            int resultCode = httpConn.getResponseCode();
            if (HttpURLConnection.HTTP_OK == resultCode) {
                String readLine;
                BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    result.append(readLine).append("\n");
                }
                responseReader.close();
            }
        } catch (Exception e) {
            result.append("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result.toString();
    }

}

Java中使用HTTP请求调用企业微信发送文本消息的接口,你需要先获取到企业微信提供的API访问凭证,如access_token。以下是一个基本的例子,展示如何使用Apache HttpClient库来完成这个任务: ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class WechatMessageSender { private static final String魏信公众平台接口URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=<your_access_token>"; public void sendMessage(String text) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(WechatMessageSender魏信公众平台接口URL); // 设置POST数据,这里是发送文本消息的数据格式 String jsonPayload = "{\"touser\":\"@all\",\"msgtype\":\"text\",\"text\":{\"content\":\"" + text + "\"}}"; StringEntity stringEntity = new StringEntity(jsonPayload, "UTF-8"); httpPost.setEntity(stringEntity); // 发送请求 CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println("Response: " + EntityUtils.toString(entity)); } else { System.out.println("No response content"); } } finally { response.close(); } } public static void main(String[] args) throws Exception { WechatMessageSender sender = new WechatMessageSender(); String message = "Hello from Java!"; sender.sendMessage(message); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值