Java使用HTTPClient3.0.1開發的公眾平臺訊息模板的推送功能

rgqancy發表於2016-05-10

package com.company.product.manager.busniess.impl;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.ClientProtocolException;

import com.company.product.https.EasySSLProtocolSocketFactory;

/**
*
* @author Renguoqiang 微信公眾平臺,向使用者推送模板訊息服務。
*/
public class WeChatMpTemplateMessageService {
public static JSONObject get(HttpClient client, String url)
throws IOException, ClientProtocolException {
GetMethod httpGet = new GetMethod(url);
int responseGet = client.executeMethod(httpGet);
System.out.println(responseGet);
String responseText = httpGet.getResponseBodyAsString();
System.out.println(responseText);
httpGet.releaseConnection();
JSONObject result = JSONObject.fromObject(responseText);
return result;
}

public static HttpClient getClient(String url) {
HttpClient httpClient = new HttpClient();
return httpClient;
}

public static JSONObject getJSONParameters(String templateid,String openid) {
JSONObject first = new JSONObject();
first.put("value", "你好");
//first.put("color", "#C71585");

JSONObject keyword1 = new JSONObject();
keyword1.put("value", "715424629750407168");
keyword1.put("color", "#FF00FF");

JSONObject keyword2 = new JSONObject();
keyword2.put("value", "");
//keyword2.put("color", "#FF00FF");

JSONObject keyword3 = new JSONObject();
keyword3.put("value", "客服人員已經為您確定好型別和費用");
//keyword3.put("color", "#00FFFF");

JSONObject remark = new JSONObject();
remark.put("value", "請登入,確認並支付。");
//remark.put("color", "#0000FF");

JSONObject data = new JSONObject();
data.put("first", first);
data.put("keyword1", keyword1);
data.put("keyword2", keyword2);
data.put("keyword3", keyword3);
data.put("remark", remark);

JSONObject jsonParam = new JSONObject();
jsonParam.put("touser", openid);
jsonParam.put("template_id", templateid);
jsonParam.put("url", "https://www.company.com/");
jsonParam.put("data", data);
return jsonParam;
}

public static List<String> getTemplateList(HttpClient client, String access_token) {
String url = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token="
+ access_token;
JSONObject result = new JSONObject();
try {
result = get(client, url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

JSONArray jsonArray = result.getJSONArray("template_list");
System.out.println(jsonArray);

ArrayList<String> templateIdList = new ArrayList<String>();
for (Object jsonObject : jsonArray) {
templateIdList.add(((JSONObject) jsonObject)
.getString("template_id"));
}

return templateIdList;
}

public static String getTicket(HttpClient client,String appid,String appsecret)
throws IOException, ClientProtocolException {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ appid + "&secret=" + appsecret;

JSONObject result = get(client, url);

String access_token = "";
String key = "access_token";

// JSON反序列化
access_token = result.getString(key);

System.out.println("access_token:" + access_token);

return access_token;
}

public static void main(String[] args) {
// JRE設定代理伺服器
// System.setProperty("http.proxyHost", "localhost");
// System.setProperty("http.proxyPort", "8888");
// System.setProperty("https.proxyHost", "localhost");
// System.setProperty("https.proxyPort", "8888");

HttpClient client = null;
String url = "https://api.weixin.qq.com";

client = getClient(url);

// 獲得令牌
String access_token = "";
try {
String appid = "wxeadda6b8c0e02111";
String appsecret = "55d6d8b2070989df2ef7518687ec8d11";

access_token = getTicket(client,appid,appsecret);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// 獲得模板列表
List<String> templateIdList = getTemplateList(client, access_token);

// 傳送模板訊息
// for(String templateid : templateIdList){
String templateid = "QxTCrTWt4HxS3NTOt_iwzJ4gOdrHIDg1l5pfRcniBBs";
String openid="o8cOBwvAJTSPbOhOInWlb7GYdKu1";
postTemplateMsg(client, access_token, templateid,openid);
// }
}

public static void postTemplateMsg(HttpClient httpClient,
String access_token, String templateid,String openid) {
String securityServerSSLPort = "443";
String securityServerHost = "api.weixin.qq.com";
String securityServerActionUri = "cgi-bin/message/template/send?access_token="
+ access_token;
String securityServerHttpsPort = "80";

String body = getJSONParameters(templateid,openid).toString();

httpClient = getClient(securityServerHost);

Protocol easyhttps = new Protocol("https",
new EasySSLProtocolSocketFactory(),
Integer.valueOf(securityServerSSLPort));
HostConfiguration hc = new HostConfiguration();
PostMethod httpMethod = new org.apache.commons.httpclient.methods.PostMethod(
"https://" + securityServerHost + "/" + securityServerActionUri);
try {
Protocol.registerProtocol("https", easyhttps);

httpClient.getParams().setContentCharset(
StandardCharsets.UTF_8.name());

hc.setHost(securityServerHost,
Integer.valueOf(securityServerHttpsPort), easyhttps);

if (StringUtils.isNotBlank(body)) {
StringRequestEntity entity = new StringRequestEntity(body,
"application/json;charset="
+ StandardCharsets.UTF_8.name().toLowerCase(),
StandardCharsets.UTF_8.name());

httpMethod.setRequestEntity(entity);
}

int result = httpClient.executeMethod(hc, httpMethod);
System.out.println("Response status code: " + result);
System.out.println("Response body: ");
String strRespBody = httpMethod.getResponseBodyAsString();
System.out.println(strRespBody);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpMethod.releaseConnection();
}
}
}

相關文章