搜尋
首頁微信小程式微信開發利用java開發微信實作微信主動推播訊息實例

這篇文章主要介紹了利用java開發微信實現微信主動推播訊息實例,需要的朋友可以參考下


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;
 }
}


以上是利用java開發微信實作微信主動推播訊息實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境