Java调用微信发送文本接口

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();
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值