代碼結構
pom.xml
<!--微信公衆號-->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>${weixin-java-mp.version}</version>
</dependency>
AbstractBuilder.java
package com.xd.common.wx.mp.builder;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractBuilder {
protected final Logger logger = LoggerFactory.getLogger(getClass());
public abstract WxMpXmlOutMessage build(String content,
WxMpXmlMessage wxMessage, WxMpService service);
}
ImageBuilder.java
package com.xd.common.wx.mp.builder;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutImageMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
public class ImageBuilder extends AbstractBuilder {
@Override
public WxMpXmlOutMessage build(String content, WxMpXmlMessage wxMessage,
WxMpService service) {
WxMpXmlOutImageMessage m = WxMpXmlOutMessage.IMAGE().mediaId(content)
.fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
.build();
return m;
}
}
TextBuilder.java
package com.xd.common.wx.mp.builder;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
public class TextBuilder extends AbstractBuilder {
@Override
public WxMpXmlOutMessage build(String content, WxMpXmlMessage wxMessage,
WxMpService service) {
WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(content)
.fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
.build();
return m;
}
}
微信公衆號關注自動回覆文本信息
package com.xd.common.wx.mp.handler;
import com.xd.common.wx.mp.builder.TextBuilder;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @author Binary Wang(https://github.com/binarywang)
*/
@Component
public class SubscribeHandler extends AbstractHandler {
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
Map<String, Object> context, WxMpService weixinService,
WxSessionManager sessionManager) throws WxErrorException {
this.logger.info("新關注用戶 OPENID: " + wxMessage.getFromUser());
// 獲取微信用戶基本信息
try {
WxMpUser userWxInfo = weixinService.getUserService()
.userInfo(wxMessage.getFromUser(), null);
if (userWxInfo != null) {
// TODO 可以添加關注用戶到本地數據庫
}
} catch (WxErrorException e) {
if (e.getError().getErrorCode() == 48001) {
this.logger.info("該公衆號沒有獲取用戶信息權限!");
}
}
WxMpXmlOutMessage responseResult = null;
try {
responseResult = this.handleSpecial(wxMessage);
} catch (Exception e) {
this.logger.error(e.getMessage(), e);
}
if (responseResult != null) {
return responseResult;
}
try {
String str="推送文本";
return new TextBuilder().build(str, wxMessage, weixinService);
} catch (Exception e) {
this.logger.error(e.getMessage(), e);
}
return null;
}
/**
* 處理特殊請求,比如如果是掃碼進來的,可以做相應處理
*/
private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
throws Exception {
//TODO
return null;
}
}
具體部分代碼
/**
*@Author zcm
*@Email [email protected]
*@Description 自動回覆 一條消息
*@Date 14:21 2020/4/24
*/
//第一句,設置服務器端編碼
response.setCharacterEncoding("utf-8");
//第二句,設置瀏覽器端解碼
response.setContentType("text/xml;charset=utf-8");
String str = "你好呀!歡迎來到我的微信公衆號。\n\n";
//創建消息文本
WxMpXmlOutTextMessage text = WxMpXmlOutTextMessage.TEXT().toUser(fromUser).fromUser(toUser).content(str).build();
String xml = text.toXml();
PrintWriter out = null;
try {
out = response.getWriter();
out.print(xml);
} catch (IOException e) {
out.close();
out = null;
e.printStackTrace();
}
out.close();
out = null;
//第二條信息 使用客服模式推送
String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + access_token;
JSONObject object = new JSONObject();
object.put("touser", fromUser);
object.put("msgtype", "image");
JSONObject object1 = new JSONObject();
object1.put("media_id", "WNtGBTNVULve98fkEJWUnDIMZZGlWEpONV2NK50un_U_12211");
object.put("image", object1);
System.out.println("JSONObject:" + object);
HttpUtil.post(url, object.toJSONString());
HttpUtil.java
media_id需要在公衆號素材裏面上傳,然後獲取放media_id參數裏去
package com.xd.common.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.CharEncoding;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Map;
/**
* HTTP幫助類
*
* @Author sfh
* @Date 2019/11/18 14:37
*/
@Slf4j
public class HttpUtil {
// private static CloseableHttpClient httpClient;
//
// static {
// PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// cm.setMaxTotal(100);
// cm.setDefaultMaxPerRoute(20);
// cm.setDefaultMaxPerRoute(50);
// httpClient = HttpClients.custom().setConnectionManager(cm).build();
// }
/**
* 發送post請求,獲取訪問令牌
* 參數是url,json對象
*/
public static String doPostBodyByJson(String url, String param) {
try {
StringEntity stringEntity = new StringEntity(param, CharEncoding.UTF_8);
return doPost(url, stringEntity, CharEncoding.UTF_8, ContentType.APPLICATION_JSON);
} catch (Exception e) {
log.error("doPostBodyByJson", e);
}
return null;
}
/**
* 發送 表單 POST請求
*
* @Author sfh
* @Date 2019/11/12 11:33
*/
public static String doPostFormToMap(String url, Map<String, Object> map) {
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
if (map != null) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
nameValuePairs.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
}
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs, CharEncoding.UTF_8);
return doPost(url, urlEncodedFormEntity, CharEncoding.UTF_8, ContentType.APPLICATION_FORM_URLENCODED);
} catch (Exception e) {
log.error("doPostForm", e);
}
return null;
}
/**
* 通過反射獲取參數
* 表單提交
*
* @param url
* @param info
* @return
*/
public static String doPostFormToObject(String url, Object info) {
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
if (info != null) {
Class<?> aClass = info.getClass();
Field[] declaredFields = aClass.getDeclaredFields();
for (Field f : declaredFields) {
String key = f.getName();
Object value = f.get(info);
if (value == null) {
continue;
}
nameValuePairs.add(new BasicNameValuePair(key, String.valueOf(value)));
}
}
//將post請求設置請求實體
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs, CharEncoding.UTF_8);
return doPost(url, urlEncodedFormEntity, CharEncoding.UTF_8, ContentType.APPLICATION_FORM_URLENCODED);
} catch (Exception e) {
log.error("doPostForm", e);
}
return null;
}
/**
* post 請求底層封裝
*
* @param url 請求地址
* @param paramEntity 數據實體
* @param charset 編碼格式
* @param contentType 請求類型
* @return String 返回數據
*/
public static String doPost(String url, HttpEntity paramEntity, String charset, ContentType contentType) {
//創建默認httpclient實例
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
//創建post請求實例
HttpPost httpPost = new HttpPost(url);
//創建接受對象
String result = null;
httpPost.setHeader("content-type", contentType.getMimeType());
//設置請求頭
//將post請求設置請求實體
httpPost.setEntity(paramEntity);
//執行請求
//接收響應
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
//處理響應結果,從響應結果中獲取httpentity
HttpEntity entity = httpResponse.getEntity();
//判斷entity
if (entity != null) {
result = EntityUtils.toString(entity, charset);
}
return result;
} catch (IOException e) {
log.error("doPost 基礎封裝", e);
} finally {
//釋放資源
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String sendGet(String url, String param) {
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
String urlNameString = url + "?" + param;
HttpGet httpGet = new HttpGet(urlNameString);
httpGet.setHeader("accept", "*/*");
httpGet.setHeader("connection", "Keep-Alive");
httpGet.setHeader("album-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
CloseableHttpResponse execute = httpClient.execute(httpGet);
HttpEntity entity = execute.getEntity();
//判斷entity
if (entity != null) {
result = EntityUtils.toString(entity, CharEncoding.UTF_8);
}
return result;
} catch (Exception e) {
log.error("doGET", e);
} finally {
try {
if (httpClient != null) {
httpClient.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return null;
}
/**
* 根據url和請求參數獲取URI
*/
public static URI getURIwithParams(String url, MultiValueMap<String, String> params) {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParams(params);
return builder.build().encode().toUri();
}
/**
* 獲取用戶IP地址
*/
public static String getIpAddress(HttpServletRequest request) {
String[] ipHeaders = {"x-forwarded-for", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};
String[] localhostIp = {"127.0.0.1", "0:0:0:0:0:0:0:1"};
String ip = request.getRemoteAddr();
for (String header : ipHeaders) {
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
break;
}
ip = request.getHeader(header);
}
for (String local : localhostIp) {
if (ip != null && ip.equals(local)) {
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException ignored) {
}
break;
}
}
if (ip != null && ip.length() > 15 && ip.contains(",")) {
ip = ip.substring(0, ip.indexOf(','));
}
return ip;
}
public static String get(String url) {
CloseableHttpResponse response = null;
String result = "";
try {
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
httpGet.setConfig(requestConfig);
httpGet.setConfig(requestConfig);
httpGet.addHeader("Content-type", "application/json; charset=utf-8");
httpGet.setHeader("Accept", "application/json");
CloseableHttpClient httpClient = HttpClients.createDefault();
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
// 判斷返回狀態是否爲200
//判斷entity
if (entity != null) {
result = EntityUtils.toString(entity, CharEncoding.UTF_8);
}
return result;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != response) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String post(String url, String jsonString) {
CloseableHttpResponse response = null;
BufferedReader in = null;
String result = "";
try {
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
httpPost.setConfig(requestConfig);
httpPost.setConfig(requestConfig);
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
CloseableHttpClient httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, CharEncoding.UTF_8);
}
return result;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != response) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* @Author: FJW
* @Date: 2020/3/3 10:01
* @desc get請求, map封裝請求參數, 請求格式form
*/
public static String doGetByMap(String url, Map<String, String> params) {
//客戶端
CloseableHttpClient httpClient = HttpClients.createDefault();
//封裝請求參數
ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
//響應結果
String responStr = "";
CloseableHttpResponse response = null;
try {
//封裝uri及參數
URIBuilder builder = new URIBuilder(url);
builder.setParameters(pairs);
//get請求對象
HttpGet httpGet = new HttpGet(builder.build());
response = httpClient.execute(httpGet);
//判斷返回結果
if (response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
responStr = EntityUtils.toString(entity);
}
return responStr;
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeClient(httpClient, response);
}
return responStr;
}
/**
* @Author: FJW
* @Date: 2020/3/3 10:01
* @desc post請求, map封裝請求參數, 請求頭格式json
*/
public static String doPostByMap(String url, String type, Map<String, String> params) {
//客戶端
CloseableHttpClient httpClient = HttpClients.createDefault();
//封裝請求參數
ArrayList<NameValuePair> pairs = new ArrayList<>();
for (Map.Entry<String, String> entry : params.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
//響應結果
String responStr = "";
CloseableHttpResponse response = null;
try {
//封裝uri及參數
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
//設置請求頭
if ("json".equals(type)) {
httpPost.setHeader("content-type", "application/json");
} else if ("form".equals(type)) {
httpPost.setHeader("content-type", "application/x-www-form-urlencoded");
}
response = httpClient.execute(httpPost);
//判斷返回結果
if (response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
responStr = EntityUtils.toString(entity);
}
return responStr;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeClient(httpClient, response);
}
return responStr;
}
private static void closeClient(CloseableHttpClient httpClient, CloseableHttpResponse response) {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @Author: FJW
* @Date: 2020/3/3 10:02
* @desc post請求, map封裝請求參數, 請求頭格式json
*/
public static String doPostByJson(String url, String type, String jsonParams) {
//客戶端
CloseableHttpClient httpClient = HttpClients.createDefault();
//響應結果
String responStr = "";
CloseableHttpResponse response = null;
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new ByteArrayEntity(jsonParams.getBytes("UTF-8")));
//設置請求頭
if ("json".equals(type)) {
httpPost.setHeader("content-type", "application/json");
} else if ("form".equals(type)) {
httpPost.setHeader("content-type", "application/x-www-form-urlencoded");
}
System.out.println("發送請求:" + url);
response = httpClient.execute(httpPost);
//判斷返回結果
if (response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
responStr = EntityUtils.toString(entity);
System.out.println("entity:" + responStr);
}
return responStr;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeClient(httpClient, response);
}
return responStr;
}
}