HttpClient enables mass mailing of WeChat public accounts and httpclient Public Accounts

Source: Internet
Author: User
Tags log log openid

HttpClient implements mass mailing of Public numbers and httpclient public

1. Implement Functions

Send messages to users who have followed the public account. (It can be a collection of all users or users that provide openid)

2. Basic Steps

Prerequisites:

  Authenticated public account or test public account

Message sending steps:

Information about related interfaces can be viewed: http://www.cnblogs.com/0201zcr/p/5866296.html has a test account application + Get access_token and send the message url and related parameter requirements. The meaning of each parameter.

3. Practice

Here, the HttpClient sends a request to the relevant interface.

1) maven dependency

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

2) httpClient usage

It is easy to use HttpClient to send requests and receive responses. It generally takes the following steps.

3) instance

1. Request sending class

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. apac He. 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; im Port 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. s Sl. 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 {/*** get token interface */private String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/toke N? Grant_type = client_credential & appid = {0} & secret = {1} ";/*** pull user information interface */private String getUserInfoUrl =" https://api.weixin.qq.com/cgi-bin/user/info? Access_token = {0} & openid = {1} ";/*** push information interface (Group) */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 initialize and create WebClient */public void initWebClient () {log.info ("initWebClient start .... "); try {PoolingClientConnectionManager tcm = new PoolingClientConnectionManager (); tcm. setMaxTotal (10); SSLContext ctx = SSLContext. getInstan Ce ("TLS"); X509TrustManager tm = new X509TrustManager () {@ Override public void checkClientTrusted (java. security. cert. x509Certificate [] x509Certificates, String s) throws java. security. cert. certificateException {}@ Override public void checkServerTrusted (java. security. cert. x509Certificate [] x509Certificates, String s) throws java. security. cert. certificateException {}@ Override public java. securi Ty. 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 get authorization 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); S Tring response = executeHttpGet (url); Map map = JsonUtils. jsonToMap (response); accessToken = (String) map. get ("access_token");/* 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 push info * @ par Am 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 (); // The data in json format must be valid. For the meaning of each field, see the preceding connection description, the test after content is the data to be sent to the user. Here, it is sent to all people in a group msg = "{\" filter \ ": {\" is_to_all \ ": true }, \ "text \": {\ "content \": \ "test \" },\ "msgtype \": \ "text \"}\""; // set the message sending parameter StringEntity entity = new StringEntity (msg); // solve the Chinese garbled problem entity. setContentEncoding ("UTF-8"); entity. setContentType ("application/json"); post. setEntity (entity); // sends the request St Ring response = (String) this.webClient.exe cute (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 initiate an http get request to return data * @ param url * @ return * @ throws IOException * @ throws ClientProtocolException */private Str Ing executeHttpGet (String url) throws IOException, ClientProtocolException {ResponseHandler <?> ResponseHandler = new BasicResponseHandler (); String response = (String) this.webClient.exe cute (new HttpGet (url), responseHandler ); log.info ("return response ==== start ===="); log.info (response ); log.info ("return response ==== end ===="); return response ;}}

2. Controller and Service layer call

@ RequestMapping (value = "/testHttpClient", method = RequestMethod. GET) public DataMap test () {WechatAPIHander wechatAPIHander = new WechatAPIHander (); // GET access_token
// The first parameter is your appid, and the second parameter is your key. You need to change the String accessToken = wechatAPIHander according to your actual situation. getAccessToken ("appid", "scerpt"); // send the wechatAPIHander message. sendMessage (accessToken, "Test Data"); return new DataMap (). addAttribute ("DATA", accessToken );}

3. Results

If you have followed the public account to see the test message you just sent.

HttpClient document: https://pan.baidu.com/s/1miO1eOg

Thank you! Thank you for reading this article.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.