标签:
微信企业号开发,数据访问格式分为以下三种:
1、企业应用调用企业号提供的接口,管理或查询企业号后台所管理的资源、或给成员发送消息等,以下称主动调用模式。
2、企业号把用户发送的消息或用户触发的事件推送给企业应用,由企业应用处理,以下称回调模式。
3、用户在微信中阅读企业应用下发的H5页面,该页面可以调用微信提供的原生接口,使用微信开放的终端能力,以下称JSAPI模式;
官方文档地址:http://qydev.weixin.qq.com/wiki/index.php
现在我们来看一下主动调用模式的AccessToken申请,为什么需要申请AccessToken呢?文档指出
---------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------
主动调用是最基本的连接模式,当你的应用调用企业号时,需使用https协议、Json数据格式、UTF8编码,访问域名为https://qyapi.weixin.qq.com,数据包不需要加密。
在每次主动调用企业号接口时需要带上AccessToken参数,
AccessToken是企业号的全局唯一票据,调用接口时需携带AccessToken。
AccessToken需要用CorpID和Secret来换取,正常情况下AccessToken有效期为7200秒,有效期内重复获取返回相同结果,并自动续期。
由于获取access_token的api调用次数非常有限,建议应用存储与更新access_token,频繁刷新access_token会导致api调用受限,影响自身业务。
---------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------
所以AccessToken是主动调用模式中必须要申请的,也应该是首要要做的事。
后台访问连接采用的是apache提供的httpcomponents-client-4.4.1包,代码如下:
//获取微信token
public static String getToken(String corpid,String corpsecret){
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
//利用get形式获得token
HttpGet httpget = new HttpGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret);
// Create a custom response handler
ResponseHandler<JSONObject> responseHandler = new ResponseHandler<JSONObject>() {
public JSONObject handleResponse(
final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
if(null!=entity){
String result= EntityUtils.toString(entity);
//根据字符串生成JSON对象
JSONObject resultObj = JSONObject.fromObject(result);
return resultObj;
}else{
return null;
}
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
};
//返回的json对象
JSONObject responseBody = httpclient.execute(httpget, responseHandler);
String token="";
if(null!=responseBody){
token= (String) responseBody.get("access_token");//返回token
}
//System.out.println("----------------------------------------");
//System.out.println("access_token:"+responseBody.get("access_token"));
//System.out.println("expires_in:"+responseBody.get("expires_in"));
httpclient.close();
return token;
}catch (Exception e) {
e.printStackTrace();
return "";
}
}
使用的代码包下载地址(不含JCE包):http://download.csdn.net/detail/myfmyfmyfmyf/8624491 ,下载的lib包不含JCE的包,JCE包是在回调模式中需要的,需要根据本机的jdk版本做相应的下载
标签:
原文地址:http://blog.csdn.net/myfmyfmyfmyf/article/details/45221973