微信公众号,通过客服接口向指定用户推送信息

  • Post author:
  • Post category:其他


1、项目背景。根据公司需要、需要通过微信来向指定用户发送相应的消息。

2、实现步骤:

1)用户关注公众号、将用户的openId保存起来

2)通过appid和secret来获取access_token

3)通过客服接口发送信息

3、代码

获取access_token的代码片段,其中grant_type为固定的client_credential,appid和secret是申请公众号,微信给你的

/**
     * 获取access_token
     */
	public void getAccessToken(){
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx0bed7b708dd91237357&secret=66df95af6bc0bd803db86f58f1d161964133";
		int count = 1;
		String result = "";
		Map<String,Object> map = new HashMap<>();
		map.put("id", 1);
		while(true){
			try{
				result = HttpClientUtils.httpGet(url);
				JSONObject json = JSON.parseObject(result);
				if("".equals(json.getString("access_token")) || json.getString("access_token") == null){
					throw new Exception("token获取失败");
				}else{
					map.put("token", json.getString("access_token"));
					map.put("error", "");
					map.put("update_time",new Date());
					wxDao.updateToken(map);
				}
				break;
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				if(count >= 5){
					map.put("error", result);
					map.put("update_time",new Date());
					wxDao.updateToken(map);
					break;
				}
				count++;
			}
		}
    }

发送消息

/**
	 * 发送信息
	 * @param content
	 * @param openId
	 */
	public void sendMessage(String content,String openId){
		String result = "";
		Map<String,Object> token = wxDao.getToken();
		Map<String,Object> userInfo = findUserByOpenId(openId);
		Map<String,Object> log = new HashMap<>();
        log.put("open_id", openId);
		log.put("name", String.valueOf(userInfo.get("user_name")));
		String sendUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+String.valueOf(token.get("token"));
		SendTestMessage testMessage=new SendTestMessage();
		testMessage.setMsgtype("text");
        testMessage.setTouser(openId);
        Map<String,Object> map = new HashMap<>();
        map.put("content", content);
        log.put("content", content);
        testMessage.setText(map);
        String jsonTestMessage = JSONObject.toJSONString(testMessage);
        int count = 1;
        while(true){
        	try{
        		result = HttpClientUtils.sendPost(sendUrl,jsonTestMessage);
        		JSONObject json = JSON.parseObject(result);
        		if(!"0".equals(json.getString("errcode"))){
        			throw new Exception("发送失败");
        		}else{
        			log.put("status", "发送成功");
        			log.put("send_time", new Date());
        			wxDao.insertSendLog(log);
        			break;
        		}
        	}catch(Exception e){
				e.printStackTrace();
			}finally{
				if(count >= 5){
					log.put("status", "发送失败");
					log.put("error", result);
					map.put("send_time",new Date());
					wxDao.insertSendLog(log);
					break;
				}
				count++;
			}
        }
	}


Map<String,Object> token = wxDao.getToken();

此句是从数据库中获取access_token,因为access_token是每2小时失效、所以此处做了一个定时任务,每2小时获取一次access_token,并将它存在数据库中。每次发送信息时,从数据库拿出access_token。

发送请求接口

package com.wx.common.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 * httpClient
 * @author xuchangcheng
 * 2018年8月21日
 *
 */
public class HttpClientUtils {
	
	/**
	 * get请求
	 * @param url
	 * @return
	 */
	public static String httpGet(String url){
		String result = null;
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); // 连接超时时间
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 90000);  // 数据传输时间
		HttpGet get = new HttpGet(url);
		// 设置请求头
		get.setHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
		try {
			HttpResponse response = httpClient.execute(get);
			result = reponse2String(response);	
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 关闭
        httpClient.getConnectionManager().shutdown();
		return result;
	}
    
	/**
	 * post请求
	 * @param url
	 * @param params
	 * @return
	 */
	public static String httpPost(String url,Map<String,Object> params){
		String result = null;
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); // 连接超时时间
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 90000);  // 数据传输时间
		HttpPost post = null;
		post = new HttpPost(url);
        // 设置请求头
        post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
        // 参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        for(String key:keySet){
        	list.add(new BasicNameValuePair(key, params.get(key).toString()));
        }
        try {
			post.setEntity(new UrlEncodedFormEntity(list,HTTP.UTF_8));
			HttpResponse response = httpClient.execute(post);
			result = reponse2String(response);	
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
        // 关闭
        httpClient.getConnectionManager().shutdown();
        return result;
	}
	
	/**
	 * post请求
	 * @param url
	 * @param params
	 * @return
	 */
	public static String httpPostJson(String url,String params){
		String result = null;
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); // 连接超时时间
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 90000);  // 数据传输时间
		HttpPost post = null;
		post = new HttpPost(url);
        try {
        	StringEntity s = new StringEntity(params);
        	s.setContentEncoding("utf-8");
            s.setContentType("application/json; charset=utf-8");
            System.out.println(s);
            post.setEntity(s);
			HttpResponse response = httpClient.execute(post);
			result = reponse2String(response);	
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
        // 关闭
        httpClient.getConnectionManager().shutdown();
        return result;
	}
	
	/**
	 * get请求(爬虫)
	 * @param url
	 * @return
	 * @throws Exception 
	 * @throws  
	 */
	public static String httpReptileGet(String url,String cookie,String tk) throws Exception{
		String result = null;
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); // 连接超时时间
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 90000);  // 数据传输时间
		HttpGet get = new HttpGet(url);
		// 设置请求头
		//get.setHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
		get.setHeader("Cookie",cookie);
		get.setHeader("tk",tk);
		HttpResponse response = httpClient.execute(get);
		result = reponse2String(response);	
		// 关闭
        httpClient.getConnectionManager().shutdown();
		return result;
	}
	
	/**
	 * post请求(爬虫)
	 * @param url
	 * @param params
	 * @return
	 */
	public static String httpReptilePost(String url,Map<String,String> params,String cookie,String tk){
		String result = null;
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); // 连接超时时间
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 90000);  // 数据传输时间
		HttpPost post = null;
		post = new HttpPost(url);
        // 设置请求头
        post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
        post.setHeader("Cookie",cookie);
        post.setHeader("tk",tk);
        // 参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        for(String key:keySet){
        	list.add(new BasicNameValuePair(key, params.get(key)));
        }
        try {
			post.setEntity(new UrlEncodedFormEntity(list,HTTP.UTF_8));
			HttpResponse response = httpClient.execute(post);
			result = reponse2String(response);	
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
        // 关闭
        httpClient.getConnectionManager().shutdown();
        return result;
	}
	
	/**
	 * post请求,返回状态码
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception 
	 */
	public static String httpPost(String url,Map<String,String> params,String cookie,String tk) throws Exception{
		String result = null;
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); // 连接超时时间
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 90000);  // 数据传输时间
		HttpPost post = null;
		post = new HttpPost(url);
        // 设置请求头
        post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
        post.setHeader("Cookie",cookie);
        post.setHeader("tk",tk);
        // 参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        for(String key:keySet){
        	list.add(new BasicNameValuePair(key, params.get(key)));
        }
		post.setEntity(new UrlEncodedFormEntity(list,HTTP.UTF_8));
		HttpResponse response = httpClient.execute(post);
		result = String.valueOf(response.getStatusLine().getStatusCode());
        // 关闭
        httpClient.getConnectionManager().shutdown();
        return result;
	}
	
	/**
	 * post请求,返回状态码(vivo请求,需要格式化参数,单独写)
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception 
	 */
	public static String httpVivoPost(String url,Map<String,String> params,String cookie) throws Exception{
		String result = null;
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); // 连接超时时间
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 90000);  // 数据传输时间
		HttpPost post = null;
		post = new HttpPost(url);
        // 设置请求头
        post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
        post.setHeader("Cookie",cookie);
        // 参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        for(String key:keySet){
        	if(key.indexOf("ideaUpdateRequest.wordList")!=-1){
        		list.add(new BasicNameValuePair("ideaUpdateRequest.wordList", params.get(key)));
        	}else{
        		list.add(new BasicNameValuePair(key, params.get(key)));
        	}
        }
		post.setEntity(new UrlEncodedFormEntity(list,HTTP.UTF_8));
		HttpResponse response = httpClient.execute(post);
		result = String.valueOf(response.getStatusLine().getStatusCode());
        // 关闭
        httpClient.getConnectionManager().shutdown();
        return result;
	}
	
	/**
	 * 获取客户端ip(外网)
	 * @param request
	 * @return
	 */
	public static String getIp(HttpServletRequest request){
		 String ip = request.getHeader("X-Forwarded-For");  
         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))  
            ip = request.getHeader("Proxy-Client-IP");  
         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))  
            ip = request.getHeader("WL-Proxy-Client-IP");  
         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))  
            ip = request.getHeader("HTTP_CLIENT_IP");  
         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))  
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))  
            ip = request.getRemoteAddr();  
         if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip))  
            try {  
                ip = InetAddress.getLocalHost().getHostAddress();  
            }  
            catch (UnknownHostException unknownhostexception) {  
         }  
	     return ip;
	}
	
	/**
	 * 转化返回参数
	 * @param response
	 * @return
	 */
	public static String reponse2String(HttpResponse response){
		HttpEntity entity = response.getEntity();
		String body = null;
		try {
			body = EntityUtils.toString(entity);
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return body;
	}
	
	
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			//设置通用的请求属性
			conn.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
			out = new PrintWriter(outWriter);
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				in = new BufferedReader(new InputStreamReader(conn.getInputStream()));result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常!"+e);
			e.printStackTrace();
		}
		//使用finally块来关闭输出流、输入流
		finally{
			try{
				if(out!=null){
					out.close();
				}
				if(in!=null){
					in.close();
				}
			}
			catch(IOException ex){
				ex.printStackTrace();
			}
		}
		return result;
	}  
}

有喜欢的朋友可以关注下头条号《

老徐聊技术



版权声明:本文为xcc_2269861428原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。