代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
Java
】
获取微信用户基本信息
作者:
睿童
/ 发布于
2017/1/18
/
576
1.微信使用https协议,so,编写https工具类: package com.lishidao.app.controller; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.URL; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HttpsUtil { /** log记录 */ protected static final Logger log = LoggerFactory .getLogger(HttpsUtil.class); private static final String METHOD_POST = "POST"; private static final String DEFAULT_CHARSET = "utf-8"; public static String doPost(String url, String params, String charset, int connectTimeout, int readTimeout) throws Exception { String ctype = "application/json;charset=" + charset; byte[] content = {}; if (params != null) { content = params.getBytes(charset); } return doPost(url, ctype, content, connectTimeout, readTimeout); } public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout) throws Exception { HttpsURLConnection conn = null; OutputStream out = null; String rsp = null; try { try { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(ctx); conn = getConnection(new URL(url), METHOD_POST, ctype); conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); } catch (Exception e) { log.error("GET_CONNECTOIN_ERROR, URL = " + url, e); throw e; } try { out = conn.getOutputStream(); out.write(content); rsp = getResponseAsString(conn); } catch (IOException e) { log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e); throw e; } } finally { if (out != null) { out.close(); } if (conn != null) { conn.disconnect(); } } return rsp; } private static class DefaultTrustManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } private static HttpsURLConnection getConnection(URL url, String method, String ctype) throws IOException { HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod(method); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html"); conn.setRequestProperty("User-Agent", "stargate"); conn.setRequestProperty("Content-Type", ctype); return conn; } protected static String getResponseAsString(HttpURLConnection conn) throws IOException { String charset = getResponseCharset(conn.getContentType()); InputStream es = conn.getErrorStream(); if (es == null) { return getStreamAsString(conn.getInputStream(), charset); } else { String msg = getStreamAsString(es, charset); if (StringUtils.isEmpty(msg)) { throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage()); } else { throw new IOException(msg); } } } private static String getStreamAsString(InputStream stream, String charset) throws IOException { try { BufferedReader reader = new BufferedReader(new InputStreamReader( stream, charset)); StringWriter writer = new StringWriter(); char[] chars = new char[256]; int count = 0; while ((count = reader.read(chars)) > 0) { writer.write(chars, 0, count); } return writer.toString(); } finally { if (stream != null) { stream.close(); } } } private static String getResponseCharset(String ctype) { String charset = DEFAULT_CHARSET; if (!StringUtils.isEmpty(ctype)) { String[] params = ctype.split(";"); for (String param : params) { param = param.trim(); if (param.startsWith("charset")) { String[] pair = param.split("=", 2); if (pair.length == 2) { if (!StringUtils.isEmpty(pair[1])) { charset = pair[1].trim(); } } break; } } } return charset; } public static void main(String[] args) throws Exception{ String url = "https://www.baidu.com"; String params = "v=1&r=2"; String result = HttpsUtil.doPost(url, params, "UTF-8", 5000, 5000); System.out.println(result); } } 2.编写微信用户基本信息对应类。 package com.lishidao.app.controller; public class WeiXinUser { public String subscribe; public String openid; public String nickname; public String sex; public String language; public String city; public String province; public String country; public String headimgurl; public String subscribe_time; public String unionid; public String getSubscribe() { return subscribe; } public void setSubscribe(String subscribe) { this.subscribe = subscribe; } public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getHeadimgurl() { return headimgurl; } public void setHeadimgurl(String headimgurl) { this.headimgurl = headimgurl; } public String getSubscribe_time() { return subscribe_time; } public void setSubscribe_time(String subscribe_time) { this.subscribe_time = subscribe_time; } public String getUnionid() { return unionid; } public void setUnionid(String unionid) { this.unionid = unionid; } public String toString() { return subscribe + "|" + openid + "|" + nickname + "|" + sex + "|" + language + "|" + city + "|" + province + "|" + country + "|" + headimgurl + "|" + subscribe_time + "|" + unionid; } } 3.编写微信工具类 package com.lishidao.app.controller; import java.util.Date; import java.util.HashMap; import java.util.Map; import com.alibaba.fastjson.JSONObject; import framecore.util.DateUtil; public class WeiXinUtil { private static final Map<String, String> tokenMap = new HashMap<String, String>(); private static String appid = "APPID"; private static String secret = "SECRET"; public static String getToken() throws Exception { System.out.println("get token start......"); String key = DateUtil.getDateShortString(new Date()); if (tokenMap.containsKey(key)) { String token = tokenMap.get(key); System.out.println("tokenMap.token:" + token); System.out.println("get token end......"); return token; } String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret; String jsonStr = HttpsUtil.doPost(url, "", "UTF-8", 10000, 10000); System.out.println(jsonStr); JSONObject json = (JSONObject) JSONObject.parse(jsonStr); String token = json.getString("access_token"); tokenMap.clear(); tokenMap.put(key, token); System.out.println("getToken:" + token); System.out.println("get token end......"); return token; } public static WeiXinUser getWeiXinUser(String openid) throws Exception { System.out.println("get user start......"); String token = getToken(); String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token + "&openid=" + openid + "&lang=zh_CN"; String jsonStr = HttpsUtil.doPost(url, "", "UTF-8", 10000, 10000); System.out.println(jsonStr); JSONObject json = (JSONObject) JSONObject.parse(jsonStr); WeiXinUser weiXinUser = JSONObject.toJavaObject(json, WeiXinUser.class); System.out.println("get user end......"); return weiXinUser; } public static String getViewOpenid(String code) throws Exception { System.out.println("get openid start......"); String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code"; String jsonStr = HttpsUtil.doPost(url, "", "UTF-8", 10000, 10000); System.out.println(jsonStr); JSONObject json = (JSONObject) JSONObject.parse(jsonStr); String openid = json.getString("openid"); System.out.println("get openid end......"); return openid; } public static void main(String[] args) throws Exception { WeiXinUtil.getToken(); WeiXinUtil.getToken(); WeiXinUtil.getToken(); String code = "code"; WeiXinUtil.getViewOpenid(code); String openid = "openid"; WeiXinUtil.getWeiXinUser(openid); } }
试试其它关键字
同语言下
.
List 切割成几份 工具类
.
一行一行读取txt的内容
.
Java PDF转换成图片并输出给前台展示
.
java 多线程框架
.
double类型如果小数点后为零则显示整数否则保留两位小
.
将图片转换为Base64字符串公共类抽取
.
sqlParser 处理SQL(增删改查) 替换schema 用于多租户
.
JAVA 月份中的第几周处理 1-7属于第一周 依次类推 29-
.
java计算两个经纬度之间的距离
.
输入时间参数计算年龄
可能有用的
.
List 切割成几份 工具类
.
一行一行读取txt的内容
.
Java PDF转换成图片并输出给前台展示
.
java 多线程框架
.
double类型如果小数点后为零则显示整数否则保留两位小
.
将图片转换为Base64字符串公共类抽取
.
sqlParser 处理SQL(增删改查) 替换schema 用于多租户
.
JAVA 月份中的第几周处理 1-7属于第一周 依次类推 29-
.
java计算两个经纬度之间的距离
.
输入时间参数计算年龄
睿童
贡献的其它代码
(
10
)
.
校验图片的大小、尺寸、比例
.
根据分区查询数据
.
获取微信用户基本信息
.
截图生成图片并保存到相册
.
回溯法求n皇后问题
.
将一个数进行质因分解(单纯的质因分解)
.
用SQL语句断开某个数据库的所有活动连接
.
App相关辅助类
.
字符拼接
.
常用正则表达式工具RegexpUtils
Copyright © 2004 - 2024 dezai.cn. All Rights Reserved
站长博客
粤ICP备13059550号-3