[b]1.微信使用https协议,so,编写https工具类:[/b]
[b]2.编写微信用户基本信息对应类。[/b]
[b]3.编写微信工具类[/b]
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);
}
}
[b]2.编写微信用户基本信息对应类。[/b]
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;
}
}
[b]3.编写微信工具类[/b]
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);
}
}