标签:
本文转自http://www.cnblogs.com/always-online/category/598553.html
一、微信获取access_token接口简介
1、请求:该请求是GET方式请求,所以要携带的参数都是附加到url后面传递给微信服务器。请求的url格式如下:
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
其中,APPID与APPSECRET都我们开发的时候自己帐号申请的。
2、响应:返回数据都是json数据,格式如下:
正确的时候返回的数据: {"access_token":"ACCESS_TOKEN","expires_in":7200}
ACCESS_TOKEN:访问token,expires_in为过期时间
错误的时候返回的数据: {"errcode":40013,"errmsg":"invalid appid"}
errcode,为错误代码,errmsg为错误信息
具体api说明可查看文档:http://mp.weixin.qq.com/wiki/index.php?title=%E8%8E%B7%E5%8F%96access_token 。
二、关于java代码的调用
该接口可以在前台用页面ajax调用,也可以在后台用java代码调用。这里需要使用到apache的http组件httpcomponents-client,这里使用的版本为httpcomponents-client-4.2.1,下载地址为:http://hc.apache.org/downloads.cgi。需要使用到的jar文件如下:

三、代码实现
1 package com.demo.test;
2
3 import org.apache.http.HttpEntity;
4 import org.apache.http.HttpResponse;
5 import org.apache.http.HttpStatus;
6 import org.apache.http.client.HttpClient;
7 import org.apache.http.client.methods.HttpGet;
8 import org.apache.http.impl.client.DefaultHttpClient;
9 import org.apache.http.util.EntityUtils;
10
11 import com.google.gson.JsonObject;
12 import com.google.gson.JsonParser;
13
14 public class Test
15 {
16 public static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";// 获取access
17 // url
18 public static final String APP_ID = "wxa549b28c24cf341e";
19 public static final String SECRET = "78d8a8cd7a4fa700142d06b96bf44a37";
20
21 // 获取token
22 public static String getToken(String apiurl, String appid, String secret)
23 {
24 String turl = String.format(
25 "%s?grant_type=client_credential&appid=%s&secret=%s", apiurl,
26 appid, secret);
27 HttpClient client = new DefaultHttpClient();
28 HttpGet get = new HttpGet(turl);
29 JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
30 String result = null;
31 try
32 {
33 HttpResponse res = client.execute(get);
34 String responseContent = null; // 响应内容
35 HttpEntity entity = res.getEntity();
36 responseContent = EntityUtils.toString(entity, "UTF-8");
37 JsonObject json = jsonparer.parse(responseContent)
38 .getAsJsonObject();
39 // 将json字符串转换为json对象
40 if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
41 {
42 if (json.get("errcode") != null)
43 {// 错误时微信会返回错误码等信息,{"errcode":40013,"errmsg":"invalid appid"}
44 }
45 else
46 {// 正常情况下{"access_token":"ACCESS_TOKEN","expires_in":7200}
47 result = json.get("access_token").getAsString();
48 }
49 }
50 }
51 catch (Exception e)
52 {
53 e.printStackTrace();
54 }
55 finally
56 {
57 // 关闭连接 ,释放资源
58 client.getConnectionManager().shutdown();
59 return result;
60 }
61 }
62
63 public static void main(String[] args) throws Exception
64 {
65 System.out.println("=========1获取token=========");
66 String accessToken = getToken(GET_TOKEN_URL, APP_ID, SECRET);// 获取token
67 if (accessToken != null)
68 System.out.println(accessToken);
69 }
70
71 }
当token正常返回的时候会打印token,否则不会打印。
标签:
原文地址:http://www.cnblogs.com/abc8023/p/4643414.html