java公众号获取用户信息

该代码示例展示了如何使用Java进行微信OAuth2.0授权获取access_token和openid,以及创建和发送微信消息。主要涉及了HTTP请求方法(GET, POST)和Gson库来处理JSON数据。
摘要由CSDN通过智能技术生成
package com.jbossjf.bootproject.weixin.gongzhonghao;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jbossjf.bootproject.weixin.WeChatData;
import com.jbossjf.bootproject.weixin.WeChatUrlData;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

public class WeUserHelp {
    private CloseableHttpClient httpClient;

    /**
     * 用于提交登录数据
     */
    private HttpPost httpPost;

    /**
     * 用于获得登陆后页面
     */
    private HttpGet httpGet;

    public static final String CONTENT_TYPE = "Content-Type";

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static Gson gson = new Gson();

    /**
     * 微信授权请求,GET类型,获取授权响应,用于其他方法截取token
     *
     * @param Get_Token_Url
     * @return String 授权响应内容
     * @throws IOException
     */
    protected String toAuth(String Get_Token_Url) throws IOException {
        httpClient = HttpClients.createDefault();
        httpGet = new HttpGet(Get_Token_Url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        String resp = "";

        try {
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            response.close();
        }
        LoggerFactory.getLogger(getClass()).info(" resp:{}", resp);
        return resp;
    }

    /**
     * corpid应用组织编号 corpsecret应用秘钥 获取toAuth(String
     * Get_Token_Url)返回结果中键值对中access_token键的值
     *
     * @param
     */
    public   Map<String, Object> getToken(String corpid, String corpsecret,String code) throws IOException {
        String resultUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+corpid+"&secret="+corpsecret+"&code="+code+"&grant_type=authorization_code";
        //String resultUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ corpid +"&secret="+ corpsecret;
        WeUserHelp sw = new WeUserHelp();
        WeChatUrlData uData = new WeChatUrlData();
       // uData.setGet_Token_Url(corpid, corpsecret);
        String resp = sw.toAuth(resultUrl);
        System.out.println("resp=====:" + resp);
        try {
            Map<String, Object> map = gson.fromJson(resp, new TypeToken<Map<String, Object>>() {
            }.getType());
           // return map.get("access_token").toString();
            return  map;
        } catch (Exception e) {
            e.getStackTrace();
            return null;
        }
    }

    public String getOpenID(String corpid, String corpsecret,String code) throws IOException {
        String resultUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ corpid +"&secret="+ corpsecret +"&code="+ code +"&grant_type=authorization_code";

        WeUserHelp sw = new WeUserHelp();
        WeChatUrlData uData = new WeChatUrlData();
        //uData.setGet_Session_Url(corpid, corpsecret,code);
        String resp = sw.toAuth(resultUrl);
        System.out.println("resp=====:" + resp);
        try {
            Map<String, Object> map = gson.fromJson(resp, new TypeToken<Map<String, Object>>() {
            }.getType());
            return map.get("openid").toString();
        } catch (Exception e) {
            e.getStackTrace();
            return resp;
        }
    }

    /**
     * 创建微信发送请求post数据 touser发送消息接收者 ,msgtype消息类型(文本/图片等), application_id应用编号。
     * 本方法适用于text型微信消息,contentKey和contentValue只能组一对
     *
     * @param touser
     * @param msgtype
     * @param application_id
     * @param contentKey
     * @param contentValue
     * @return
     */
    public String createpostdata(String touser, String msgtype, int application_id, String contentKey,
                                 String contentValue) {
        WeChatData wcd = new WeChatData();
        wcd.setTouser(touser);
        wcd.setAgentid(application_id + "");
        wcd.setMsgtype(msgtype);
        Map<Object, Object> content = new HashMap<Object, Object>();
        content.put(contentKey, contentValue);
        wcd.setText(content);
        return gson.toJson(wcd);
    }

    /**
     * @Title  创建微信发送请求post实体,charset消息编码    ,contentType消息体内容类型,
     * url微信消息发送请求地址,data为post数据,token鉴权token
     * @param charset
     * @param contentType
     * @param url
     * @param data
     * @param token
     * @return
     * @throws IOException
     */
    public String post(String charset, String contentType, String url, String data, String token) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        httpPost = new HttpPost(url + token);
        httpPost.setHeader(CONTENT_TYPE, contentType);
        httpPost.setEntity(new StringEntity(data, charset));
        CloseableHttpResponse response = httpclient.execute(httpPost);
        String resp;
        try {
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, charset);
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
        LoggerFactory.getLogger(getClass()).info("call [{}], param:{}, resp:{}", url, data, resp);
        return resp;
    }

    /**
     * 获取微信用户信息
     * @param access_token
     * @return
     */
    public Map<String, Object> getWXInfo(String access_token, String openid)throws IOException {

        WeUserHelp sw = new WeUserHelp();
        // 获取用户信息
        String resultUrl ="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
        //String resultUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+ access_token +"&openid="+ openid +"&lang=zh_CN";
        String resp = sw.toAuth(resultUrl);
        System.out.println("resp=====:" + resp);
        try {
            Map<String, Object> map = gson.fromJson(resp, new TypeToken<Map<String, Object>>() {
            }.getType());
            return map;
        } catch (Exception e) {
            e.getStackTrace();
            return null;
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值