OpenId

package com.fh.util.tools;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.shiro.crypto.hash.SimpleHash;
import com.fh.util.MD5;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.sf.json.JSONObject;

public class GZopenId {

//公众号
private static final String OAUTHUSERINFO = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";


public static String appid = "wxb6ff1618";
public static String appsecret = "17069dbfeb6f7e38";// 秘钥


/**
* 根据code 得到openId
*/


public static String getOpenId(String code) {
String path = OAUTHUSERINFO.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code);
String openid = "";
URL myURL = null;
URLConnection httpsConn = null;
try {
myURL = new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
InputStreamReader insr = null;
BufferedReader br = null;
try {
httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
if (httpsConn != null) {
insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
br = new BufferedReader(insr);
JsonParser parser = new JsonParser(); // 创建JSON解析器
JsonObject object = (JsonObject) parser.parse(br);
System.out.println(object);
System.out.println(object.get("expires_in").getAsString());
try {
if ("7200".equals(object.get("expires_in").getAsString())) {
openid = object.get("openid").getAsString();
}
} catch (Exception e) {
openid = "46103";
}
}
} catch (IOException e1) {
openid = "46103";
System.out.println("code过时了");
}
return openid;
}


/**
* 描述:获取token
*/
public static String getAtoken() {
String access_token = "";
// 获取access_token
String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ appid + "&secret=" + appsecret);
URL myURL = null;
URLConnection httpsConn = null;
try {
myURL = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
InputStreamReader insr = null;
BufferedReader br = null;
try {
httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
if (httpsConn != null) {
insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
br = new BufferedReader(insr);
JsonParser parser = new JsonParser(); // 创建JSON解析器
JsonObject object = (JsonObject) parser.parse(br);
System.out.println(object);
access_token = object.get("access_token").getAsString();
System.out.println(access_token);
}
} catch (IOException e1) {
e1.printStackTrace();
}
return access_token;
}

/**
* 描述:获取jsapiTicket
*/
public static String getJSApiTicket(String acess_token) {
String ticket = "";
//获取token
        //String acess_token= GZopenId.getAtoken();
        String urlStr = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+acess_token+"&type=jsapi";  
        URL myURL = null;
URLConnection httpsConn = null;
try {
myURL = new URL(urlStr);
} catch (MalformedURLException e) {
e.printStackTrace();
}
InputStreamReader insr = null;
BufferedReader br = null;
try {
httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
if (httpsConn != null) {
insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
br = new BufferedReader(insr);
JsonParser parser = new JsonParser(); // 创建JSON解析器
JsonObject object = (JsonObject) parser.parse(br);
ticket  = object.get("ticket").getAsString();
System.out.println(ticket);
}
} catch (IOException e1) {
e1.printStackTrace();
}
return ticket;
}
//获取sign
public static Map<String, String> getSign(String url,String jsapi_ticket) {  
    Map<String, String> ret = new HashMap<String, String>(); 
        String noncestr =  getNonceStr();  
        String timestamp =  getTimeStamp();  
        String sign = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;  
        sign = new SimpleHash("SHA-1", sign).toString();
        
        ret.put("url", url);  
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", noncestr);  
        ret.put("timestamp", timestamp);  
        ret.put("signature", sign);  
        return ret;  
    }  
    //获取noncestr
    private static String getNonceStr() {  
    Random random = new Random();  
        return MD5.md5(String.valueOf(random.nextInt(10000)));  
    }  
    //获取timestamp
    private static String getTimeStamp() {  
    return String.valueOf(System.currentTimeMillis() / 1000);  
    }

/**
* 描述:请求服务器方法

* @param requestUrl
* @param requestMethod
* @param outputStr
* @return
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());


SSLSocketFactory ssf = sslContext.getSocketFactory();


URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);


httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);


httpUrlConn.setRequestMethod(requestMethod);


if ("GET".equalsIgnoreCase(requestMethod)) {
httpUrlConn.connect();
}


if (outputStr != null) {
OutputStream outputStream = httpUrlConn.getOutputStream();


outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}


InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);


String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();


inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
System.out.println("Weixin server connection timed out.");
} catch (Exception e) {
System.out.println(e);
}
return jsonObject;
}
//========================================掉起发模板消息方法============================================================
public void wxPush() {
// 88
}






//掉起tocken
// ================================================获取access_token==============================================================
public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?"
+ "grant_type=client_credential&appid=APPID&secret=APPSECRET";


// 获取access_token
public static String getAccess_token() {


String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
JSONObject jsonObject = httpRequst(requestUrl, "GET", null);


System.out.println("access_token:  " + jsonObject.getString("access_token") + "============");
String access_token = jsonObject.getString("access_token");
return access_token;
}


public static JSONObject httpRequst(String requestUrl, String requetMethod, String outputStr) {
JSONObject jsonobject = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的新人管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
sslcontext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocktFactory对象
SSLSocketFactory ssf = sslcontext.getSocketFactory();


URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);


httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requetMethod);


if ("GET".equalsIgnoreCase(requetMethod))
httpUrlConn.connect();


// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}


// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);


String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonobject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
// TODO: handle exception
} catch (Exception e) {
}
return jsonobject;
}
// ================================================获取access_token==============================================================



}


// ================================================获取access_token==============================================================
class MyX509TrustManager implements X509TrustManager {


public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub


}


public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub


}


public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
//
// // ================================================获取access_token==============================================================
//
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值