概述:他妹的微信接口,从学习到现在才搞了几个,不得不说比较笨啊
代码:先写几个出来晒晒,后续的再补上,太多了。
2.1 基础设置
2.1.1 获取access_token
public class AccessToken {//验证器
private final String token;//验证码
private final Long expiresTimestemp;//有效时间
public AccessToken(String token, Long expiresTimestemp) {//构造函数
this.token = token;
this.expiresTimestemp = expiresTimestemp;
}
public String getToken() {
return token;
}
public Long getExpiresTimestemp() {
return expiresTimestemp;
}
@Override
public int hashCode() {
int hash = 7;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final AccessToken other = (AccessToken) obj;
if ((this.token == null) ? (other.token != null) : !this.token.equals(other.token)) {
return false;
}
return true;
}
@Override
public String toString() {
return "AccessToken{" + "token=" + token + ", expiresTimestemp=" + expiresTimestemp + '}';
}
}
private final String appid, secret;
private static Map<String, AccessToken> tokenMap = new HashMap<String, AccessToken>();
private final Gson gson;
private synchronized AccessToken getAccessToken() {//获取验证
AccessToken accessToken = tokenMap.get(appid);
Long now = new Date().getTime();
if (accessToken == null || now > accessToken.getExpiresTimestemp()) {
accessToken = WechatUtils.getAccessToken(appid, secret);
}
return accessToken;
}
public static AccessToken getAccessToken(String appid, String secret) {
if (appid == null || secret == null) {
throw new IllegalArgumentException("appid or secret was null.");
}
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource cosmsservice = client.resource("https://api.weixin.qq.com/cgi-bin/token");
ClientResponse clientResponse = cosmsservice
.queryParam("grant_type", "client_credential")
.queryParam("appid", appid)
.queryParam("secret", secret)
.get(ClientResponse.class);
if (clientResponse.getStatus() != 200) {
throw new IllegalStateException("status error:" + clientResponse.getStatus());
} else {
Map result = new Gson().fromJson(clientResponse.getEntity(String.class), Map.class);
if (result.get("errcode") != null) {
throw new WechatAccessException(result.get("errcode") + "", result.get("errmsg") + "");
} else {
return new AccessToken((String) result.get("access_token"), ((Double) result.get("expires_in")).longValue());
}
}
}
2.1.2 获取组