Send a special message to the public account of WeChat.

Source: Internet
Author: User

Send a special message to the public account.

Package com. YY. tuling; import java. io. unsupportedEncodingException; import net. sf. json. JSONArray; import org. apache. http. httpResponse; 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. httpClients; import org. apache. http. util. entityUtils; import org. liufeng. course. pojo. token; import com. YY. entity. receiveXmlEntity; import com. YY. util. commonUtil; import com. YY. util. formatXmlResult; public class HttpGetRequest {/*** Post Request * @ param url request address * @ param Param request content * @ return interface returned content */private static String post (String url, string param) {try {HttpPost request = new HttpPost (url); request. setEntity (new StringEntity (param, "UTF-8"); HttpResponse response = httpclients.createdefa((cmd.exe cute (r Equest); // determine whether the request is successful if (200 = response. getStatusLine (). getStatusCode () {return EntityUtils. toString (response. getEntity ();} return "";} catch (Exception e) {e. printStackTrace (); return "" ;}} public static String getExction () throws Exception {// a third-party user's unique credential String appId = "APPID "; // String appSecret = "APPSECRET"; // call the API to obtain the credential Token = CommonUtil. getToken (appId, appSecret); String param = MatXmlResult. getJsonResult (); String Url = "https://api.weixin.qq.com/cgi-bin/message/template/send? Access_token = "+ token. getAccessToken (); String result = post (Url, param); System. out. println (result); return result ;}< pre name = "code" class = "java"> package com. YY. util; import java. io. unsupportedEncodingException; import java.net. URLEncoder; import java. util. arrayList; import java. util. date; import java. util. hashMap; import java. util. list; import java. util. map; import net. sf. json. JSONArray; import net. sf. json. JS ONObject; import com. YY. entity. receiveXmlEntity;/*** Json * @ author Administrator **/public class FormatXmlResult {public static String getJsonResult () throws UnsupportedEncodingException {// JSON format data parsing object JSONObject jo = new JSONObject (); jo. put ("touser", "message recipient's OPendID"); jo. put ("template_id", "gCC5EseXsJXrLC-mOzUc9EFE3ehSH0hAApMLyWii-io"); every public account has template_id jo. put ("url", "http://www.sina.com. Cn "); // This is a message link, usually a dynamic link. Jo. put ("topcolor", "# 7B68EE"); JSONObject map11 = new JSONObject (); map11.put ("value", "The following documents must be approved! "); Map11.put (" color "," #173177 "); JSONObject map12 = new JSONObject (); map12.put (" value "," A1 "); map12.put (" color ", "#173177"); JSONObject map13 = new JSONObject (); map13.put ("value", "B2"); map13.put ("color", "#173177 "); JSONObject map14 = new JSONObject (); map14.put ("value", "C3"); map14.put ("color", "#173177"); JSONObject map15 = new JSONObject (); map15.put ("value", "Please review as soon as possible"); map15.put ("color", "#173177"); Employee employee = new Employee (); employee. setFirst (map11); employee. setKeynote1 (map12); employee. setKeynote2 (map13); employee. setKeynote3 (map14); employee. setRemark (map15); jo. put ("data", employee); return jo. toString ();}}

 
 
Package com. YY. util; import java. io. bufferedReader; import java. io. inputStream; import java. io. inputStreamReader; import java. io. outputStream; import java. io. unsupportedEncodingException; import java.net. connectException; import java.net. URL; import javax.net. ssl. httpsURLConnection; import javax.net. ssl. SSLContext; import javax.net. ssl. SSLSocketFactory; import javax.net. ssl. trustManager; import net. sf. json. JSO NException; import net. sf. json. JSONObject; import org. liufeng. course. pojo. token; import org. slf4j. logger; import org. slf4j. loggerFactory;/*** common tool class ** @ author liufeng * @ date 2013-10-17 */public class CommonUtil {private static Logger log = LoggerFactory. getLogger (CommonUtil. class); // GET the credential (GET) public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token? Grant_type = client_credential & appid = APPID & secret = APPSECRET ";/*** send https request ** @ param requestUrl request address * @ param requestMethod Request Method (GET, POST) * @ param outputStr data submitted * @ return JSONObject (through JSONObject. get (key) method to get the json object attribute value) */public static JSONObject httpsRequest (String requestUrl, String requestMethod, String outputStr) {JSONObject jsonObject = null; try {// create an SSLContext object and use the trusted manager we specified to initialize TrustMana Ger [] tm = {new MyX509TrustManager ()}; SSLContext sslContext = SSLContext. getInstance ("SSL", "SunJSSE"); sslContext. init (null, tm, new java. security. secureRandom (); // obtain the SSLSocketFactory object SSLSocketFactory ssf = SSLContext from the sslContext object. getSocketFactory (); URL url URL = new url (requestUrl); HttpsURLConnection conn = (HttpsURLConnection) URL. openConnection (); conn. setSSLSocketFactory (ssf); conn. setDoOutpu T (true); conn. setDoInput (true); conn. setUseCaches (false); // set the Request Method (GET/POST) conn. setRequestMethod (requestMethod); // when outputStr is not null, write data to the output stream if (null! = OutputStr) {OutputStream outputStream = conn. getOutputStream (); // note the encoding format outputStream. write (outputStr. getBytes ("UTF-8"); outputStream. close () ;}// read the returned content from the input stream InputStream inputStream = conn. getInputStream (); InputStreamReader inputStreamReader = new InputStreamReader (inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader (inputStreamReader); String str = null; StringBuffer buffer = new StringBuffer (); while (str = bufferedReader. readLine ())! = Null) {buffer. append (str);} // releases the resource bufferedReader. close (); inputStreamReader. close (); inputStream. close (); inputStream = null; conn. disconnect (); jsonObject = JSONObject. fromObject (buffer. toString ();} catch (ConnectException ce) {log. error ("connection timeout :{}", ce);} catch (Exception e) {log. error ("https request exception: {}", e) ;}return jsonObject ;} /*** obtain the interface Access Credential ** @ param appid credential * @ param appsecret key * @ return */public s Tatic Token getToken (String appid, String appsecret) {Token token = null; String requestUrl = token_url.replace ("APPID", appid ). replace ("APPSECRET", appsecret); // initiate a GET request to obtain the credential JSONObject jsonObject = httpsRequest (requestUrl, "GET", null); if (null! = JsonObject) {try {token = new Token (); token. setAccessToken (jsonObject. getString ("access_token"); token. setExpiresIn (jsonObject. getInt ("expires_in");} catch (JSONException e) {token = null; // get token failure log. error ("failed to get token errcode :{} errmsg :{}", jsonObject. getInt ("errcode"), jsonObject. getString ("errmsg") ;}return token;}/*** URL encoding (UTF-8) ** @ param source * @ return */public static String urlEncodeUTF8 (String source) {String result = source; try {result = java.net. URLEncoder. encode (source, "UTF-8");} catch (UnsupportedEncodingException e) {e. printStackTrace ();} return result;}/*** determine the file extension ** @ param contentType content type ** @ return */public static String getFileExt (String contentType) based on the content type) {String fileExt = ""; if ("image/jpeg ". equals (contentType) fileExt = ". jpg "; else if (" audio/mpeg ". equals (contentType) fileExt = ". mp3 "; else if (" audio/amr ". equals (contentType) fileExt = ". amr "; else if (" video/mp4 ". equals (contentType) fileExt = ". mp4 "; else if (" video/mpeg4 ". equals (contentType) fileExt = ". mp4 "; return fileExt ;}}
package com.YY.util;import java.util.Map;import net.sf.json.JSONObject;public class Employee {private JSONObject first;private JSONObject keynote1;private JSONObject keynote2;private JSONObject keynote3;private JSONObject remark;public JSONObject getFirst() {return first;}public void setFirst(JSONObject first) {this.first = first;}public JSONObject getKeynote1() {return keynote1;}public void setKeynote1(JSONObject keynote1) {this.keynote1 = keynote1;}public JSONObject getKeynote2() {return keynote2;}public void setKeynote2(JSONObject keynote2) {this.keynote2 = keynote2;}public JSONObject getKeynote3() {return keynote3;}public void setKeynote3(JSONObject keynote3) {this.keynote3 = keynote3;}public JSONObject getRemark() {return remark;}public void setRemark(JSONObject remark) {this.remark = remark;}}

Package org. liufeng. course. util; import java. security. cert. certificateException; import java. security. cert. x509Certificate; import javax.net. ssl. x509TrustManager;/*** trust manager *** @ author liufeng * @ date 2013-04-10 */public class MyX509TrustManager implements X509TrustManager {// check the client certificate public void checkClientTrusted (Credential [] chain, string authType) throws CertificateException {} // check the server certificate public void checkServerTrusted (X509Certificate [] chain, String authType) throws CertificateException {} // returns the trusted X509 Certificate array public X509Certificate [] getAcceptedIssuers () {return null ;}}

Package org. liufeng. course. pojo;/*** credential ** @ author liufeng * @ date 2013-10-17 */public class Token {// interface Access Credential private String accessToken; // credential validity period, unit: second private int expiresIn; public String getAccessToken () {return accessToken;} public void setAccessToken (String accessToken) {this. accessToken = accessToken;} public int getExpiresIn () {return expiresIn;} public void setExpiresIn (int expiresIn) {this. expiresIn = expiresIn ;}}




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.