1. Access_token을 당기십시오
2. 사용자 정보를 당기십시오
3. 메시지를 적극적으로 푸시하십시오
4. 인터페이스에는 허가가 필요한 것 같습니다
5. httpclient 4.2.3 및 Jackson 2.2.1에 의존합니다
코드 사본은 다음과 같습니다.
공개 클래스 weixinapihelper {
/**
* 토큰 인터페이스를 얻으십시오
*/
개인 문자열 getTokenurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid= {0 }&secret= {1}";
/**
* WeChat 사용자 정보 인터페이스를 당기십시오
*/
개인 문자열 getUserInfourl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token= {0 }&openid= {1}";
/**
* 활성 푸시 정보 인터페이스
*/
개인 문자열 sendmsgurl = "https://api.weixin.qq.com/cgi-bin/message/send?access_token= {0}";
개인 httpclient webclient;
개인 로그 = logfactory.getLog (getClass ());
public void initwebclient (String proxyHost, int proxyport) {
this.initwebclient ();
if (webClient! = null &&! stringUtils.isempty (proxyHost)) {
httphost proxy = 새로운 httphost (proxyhost, proxyport);
WebClient.getParams (). setParameter (connroutepnames.default_proxy, proxy);
}
}
/**
* @desc 웹 클라이언트 생성을 초기화합니다
*/
공개 void initwebclient () {
log.info ( "initwebclient start ....");
노력하다 {
PoolingClientConnectionManager TCM = New PoolingClientConnectionManager ();
tcm.setmaxtotal (10);
sslcontext ctx = sslcontext.getinstance ( "tls");
x509trustmanager tm = new x509trustmanager () {
public void checkclientTrusted (x509certificate [] arg0, String arg1) throws eptertanceateException {
}
public void checkserverTrusted (x509certificate [] arg0, string arg1)는 증명서 exception {
}
public x509certificate [] getAcceptedIssuers () {
널 리턴;
}
};
ctx.init (null, new x509trustmanager [] {tm}, null);
sslsocketfactory ssf = new sslsocketfactory (ctx, sslsocketfactory.alow_all_hostname_verifier);
체계 SCH = 새로운 체계 ( "https", 443, SSF);
tcm.getSchemeregistry (). Register (Sch);
WebClient = 새로운 defaulthttpclient (TCM);
} catch (예외) {
log.error ( "initwebclient Exception", ex);
} 마지막으로 {
log.info ( "initwebclient end ...");
}
}
/**
* @desc는 승인 된 토큰을받습니다
* @param appid
* @param 비밀
* @반품
*/
공개 문자열 getAccessToken (String Appid, String Secret) {
문자열 accessToken = null;
노력하다 {
log.info ( "getAccessToken start. {appid =" + appid + ", Secret :" + Secret + "}");
String url = messageformat.format (this.getTokenUrl, AppId, Secret);
문자열 응답 = executehttpget (url);
AccessToken = jsonutils.read (응답, "access_token");
} catch (예외 e) {
log.error ( "Access toekn Exception", e);
}
Return AccessToken;
}
/**
* @desc 푸시 정보
* @param 토큰
* @param msg
* @반품
*/
공개 문자열 sendMessage (문자열 토큰, 문자열 msg) {
노력하다{
log.info ( "sendmessage start.token :"+token+", msg :"+msg);
문자열 url = messageformat.format (this.sendmsgurl, token);
httppost post = new httppost (URL);
ResponseHandler <?> responseHandler = New BasicResponseHandler ();
엄격한 엔티티 = 새로운 엄격함 (MSG);
post.setentity (엔티티);
문자열 응답 = (string) this.webclient.execute (post, responshangher);
log.info ( "반환 응답 ====== START =====================);
log.info (응답);
log.info ( "반환 응답 ===== 종료 =====================);
반환 응답;
} catch (예외 e) {
log.error ( "사용자 정보 예외 GET", e);
널 리턴;
}
}
/**
* @desc 당기기 사용자 정보
* @param 토큰
* @param openid
* @반품
*/
공개 weixinopenuser getuserinfo (문자열 토큰, String OpenID) {
노력하다 {
log.info ( "getuserinfo start. {토큰 :" + token + ", openID :" + openID + "}");
String url = messageformat.format (this.getUserInfourl, Token, OpenID);
문자열 응답 = executehttpget (url);
JSONNODE JSON = JSONUTILS.READ (응답);
if (json.get ( "OpenId")! = null) {
weixinopenuser user = 새로운 weixinopenuser ();
user.setopenuserid (json.get ( "openid"). astext ());
user.setstate (json.get ( "구독"). 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 ());
}
리턴 사용자;
}
} catch (예외 e) {
log.error ( "사용자 정보 예외 GET", e);
}
널 리턴;
}
/**
* @DESC는 HTTP GET 요청 데이터를 반환합니다
* @param url
* @반품
* @throws ioexception
* @throws ClientProtoColexception
*/
개인 문자열 executeHttPget (String URL)은 ioException, ClientProtoColexception {
ResponseHandler <?> responseHandler = New BasicResponseHandler ();
문자열 응답 = (string) this.webclient.execute (new httpget (url), responskHandler);
log.info ( "반환 응답 ====== START =====================);
log.info (응답);
log.info ( "반환 응답 ===== 종료 =====================);
반환 응답;
}
}