日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

httpClient实现微信公众号消息群发

發布時間:2023/12/13 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 httpClient实现微信公众号消息群发 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1、實現功能 

  向關注了微信公眾號的微信用戶群發消息。(可以是所有的用戶,也可以是提供了微信openid的微信用戶集合)

2、基本步驟

前提:

  已經有認證的公眾號或者測試公眾賬號

發送消息步驟:

  • 發送一個請求微信去獲取access_token
  • 發送一個請求去請求微信發送消息
  • 相關微信接口的信息可以查看:http://www.cnblogs.com/0201zcr/p/5866296.html?有測試賬號的申請 + 獲取access_token和發送微信消息的url和相關的參數需求。各個參數的意義等。

    3、實踐

      這里通過HttpClient發送請求去微信相關的接口。

    1)maven依賴

    <dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.3.1</version> </dependency>

    2)httpClient使用方法

    使用HttpClient發送請求、接收響應很簡單,一般需要如下幾步即可。

  • 創建HttpClient對象。
  • 創建請求方法的實例,并指定請求URL。如果需要發送GET請求,創建HttpGet對象;如果需要發送POST請求,創建HttpPost對象。
  • 如果需要發送請求參數,可調用HttpGet、HttpPost共同的setParams(HetpParams params)方法來添加請求參數;對于HttpPost對象而言,也可調用setEntity(HttpEntity entity)方法來設置請求參數。
  • 調用HttpClient對象的execute(HttpUriRequest request)發送請求,該方法返回一個HttpResponse。
  • 調用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取服務器的響應頭;調用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務器的響應內容。程序可通過該對象獲取服務器的響應內容。
  • 釋放連接。無論執行方法是否成功,都必須釋放連接——這里使用了連接池,可以交給連接池去處理
  • ?3)實例

    1、發送請求的類

    import com.alibaba.druid.support.json.JSONUtils; import com.alibaba.druid.support.logging.Log; import com.alibaba.druid.support.logging.LogFactory; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.seewo.core.util.json.JsonUtils; import org.apache.commons.collections.map.HashedMap; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpHost; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType;import javax.net.ssl.SSLContext; import javax.net.ssl.X509TrustManager; import javax.security.cert.CertificateException; import javax.security.cert.X509Certificate; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.Map;/*** Created by zhengcanrui on 16/9/20.*/ public class WechatAPIHander {/*** 獲取token接口*/private String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";/*** 拉微信用戶信息接口*/private String getUserInfoUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}";/*** 主動推送信息接口(群發)*/private String sendMsgUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token={0}";private HttpClient webClient;private Log log = LogFactory.getLog(getClass());public void initWebClient(String proxyHost, int proxyPort){this.initWebClient();if(webClient != null && !StringUtils.isEmpty(proxyHost)){HttpHost proxy = new HttpHost(proxyHost, proxyPort);webClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);}}/*** @desc 初始化創建 WebClient*/public void initWebClient() {log.info("initWebClient start....");try {PoolingClientConnectionManager tcm = new PoolingClientConnectionManager();tcm.setMaxTotal(10);SSLContext ctx = SSLContext.getInstance("TLS");X509TrustManager tm = new X509TrustManager() {@Overridepublic void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {}@Overridepublic void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {}@Overridepublic java.security.cert.X509Certificate[] getAcceptedIssuers() {return new java.security.cert.X509Certificate[0];}};ctx.init(null, new X509TrustManager[] { tm }, null);SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);Scheme sch = new Scheme("https", 443, ssf);tcm.getSchemeRegistry().register(sch);webClient = new DefaultHttpClient(tcm);} catch (Exception ex) {log.error("initWebClient exception", ex);} finally {log.info("initWebClient end....");}}/*** @desc 獲取授權token* @param appid* @param secret* @return*/public String getAccessToken(String appid, String secret) {String accessToken = null;try {log.info("getAccessToken start.{appid=" + appid + ",secret:" + secret + "}");String url = MessageFormat.format(this.getTokenUrl, appid, secret);String response = executeHttpGet(url);Map map = JsonUtils.jsonToMap(response);accessToken = (String) map.get("access_token");/* Object Object = JSONUtils.parse(response);accessToken = jsonObject.getString("access_token");*/ // accessToken = JsonUtils.read(response, "access_token");} catch (Exception e) {log.error("get access toekn exception", e);}return accessToken;}/*** @desc 推送信息* @param token* @param msg* @return*/public String sendMessage(String token,String msg){try{log.info("\n\nsendMessage start.token:"+token+",msg:"+msg);String url = MessageFormat.format(this.sendMsgUrl, token);HttpPost post = new HttpPost(url);ResponseHandler<?> responseHandler = new BasicResponseHandler();//這里必須是一個合法的json格式數據,每個字段的意義可以查看上面連接的說明,content后面的test是要發送給用戶的數據,這里是群發給所有人msg = "{\"filter\":{\"is_to_all\":true},\"text\":{\"content\":\"test\"},\"msgtype\":\"text\"}\"";//設置發送消息的參數StringEntity entity = new StringEntity(msg);//解決中文亂碼的問題entity.setContentEncoding("UTF-8");entity.setContentType("application/json");post.setEntity(entity);//發送請求String response = (String) this.webClient.execute(post, responseHandler);log.info("return response=====start======");log.info(response);log.info("return response=====end======");return response;}catch (Exception e) {log.error("get user info exception", e);return null;}}/*** @desc 發起HTTP GET請求返回數據* @param url* @return* @throws IOException* @throws ClientProtocolException*/private String executeHttpGet(String url) throws IOException, ClientProtocolException {ResponseHandler<?> responseHandler = new BasicResponseHandler();String response = (String) this.webClient.execute(new HttpGet(url), responseHandler);log.info("return response=====start======");log.info(response);log.info("return response=====end======");return response;}}

    ?2、Controller和Service層調用

    @RequestMapping(value = "/testHttpClient", method = RequestMethod.GET)public DataMap test() {WechatAPIHander wechatAPIHander = new WechatAPIHander();//獲取access_token
          //第一個參數是你appid,第二個參數是你的秘鑰,需要根據你的具體情況換String accessToken = wechatAPIHander.getAccessToken("appid","scerpt"); //發送消息wechatAPIHander.sendMessage(accessToken, "測試數據");return new DataMap().addAttribute("DATA",accessToken);}

    ?3、結果

      假如你關注了微信公眾號中看到你剛剛發送的test消息。

    HttpClient學習文檔:https://pan.baidu.com/s/1miO1eOg

    ?致謝:感謝您的閱讀

    轉載于:https://www.cnblogs.com/0201zcr/p/5893600.html

    創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

    總結

    以上是生活随笔為你收集整理的httpClient实现微信公众号消息群发的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。