微信java開發之實現微信主動推送訊息_java

來源:互聯網
上載者:User


1.拉取access_token
2.拉取使用者資訊
3.主動推送訊息
4.介面貌似要申請許可權
5.依賴httpclient4.2.3 和jackson 2.2.1

複製代碼 代碼如下:

public class WeixinAPIHelper {
 /**
  * 擷取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/send?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() {

    public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

    }

    public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

    }

    public X509Certificate[] getAcceptedIssuers() {
     return null;
    }
   };
   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);
   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("sendMessage start.token:"+token+",msg:"+msg);
   String url = MessageFormat.format(this.sendMsgUrl, token);
   HttpPost post = new HttpPost(url);
   ResponseHandler<?> responseHandler = new BasicResponseHandler();
   StringEntity entity = new StringEntity(msg);
   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 拉取使用者資訊
  * @param token
  * @param openid
  * @return
  */
 public WeixinOpenUser getUserInfo(String token, String openid) {
  try {
   log.info("getUserInfo start.{token:" + token + ",openid:" + openid + "}");
   String url = MessageFormat.format(this.getUserInfoUrl, token, openid);
   String response = executeHttpGet(url);
   JsonNode json = JsonUtils.read(response);
   if (json.get("openid") != null) {
    WeixinOpenUser user = new WeixinOpenUser();
    user.setOpenUserId(json.get("openid").asText());
    user.setState(json.get("subscribe").asText());
    if ("1".equals(user.getState())) {
     user.setUserName(json.get("nickname").asText());
     user.setSex(json.get("sex").asText());
     user.setCity(json.get("city").asText());
     user.setLanguage(json.get("language").asText());
    }
    return user;
   }
  } 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;
 }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.