java开发微信服务号(三) 写一个获取accessToken接口

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


/**
 * @Auther: 抹茶冰冰冰
 * @Date: 2020-04-02
 * @Description: 获取 accessToken
 **/
@Service
public class GetAccessTokenService {

    /**
     * 这里获取的是配置文件application.properties里的部分属性的值
     * appId:开发者id
     * appsecret:开发者密码
     * accessTokenUrl:获取token的地址
     */
    @Value("${weixin.appId}")
    private String appId;
    @Value("${weixin.appsecret}")
    private String appsecret;
    @Value("${weixin.getAccessTockenUrl}")
    private String accessTockenUrl;

    /**
     * 获取accessToken
     *
     * @return
     */
    public String getAccessToken() {
        String accessToken = null;
        String newAccessTockenUrl = accessTockenUrl.replace("APPID", appId).replace("APPSECRET", appsecret);
        // 获得Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //响应模型
        CloseableHttpResponse response = null;
        try {
            //创建get请求
            HttpGet httpGet = new HttpGet(newAccessTockenUrl);
            response = httpClient.execute(httpGet);
            //获取响应实体
            HttpEntity responseEntity = response.getEntity();
            String resultDemo = EntityUtils.toString(responseEntity);
            //转换成对象,好把需要的字段对应的值拿出来
            JSONObject jsonObject = JSONObject.fromObject(resultDemo);
            accessToken= jsonObject.getString("access_token");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }

因为“公众平台以access_token为接口调用凭据,来调用接口,所有接口的调用需要先获取access_token,access_token在2小时内有效,过期需要重新获取,但1天内获取次数有限(测试账号2000次),开发者需自行存储”。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值