JAVA微信公众号(一)获取access_token

1、获取access_token
access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。

package com.wx;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.junit.Test;
import com.common.weixin.utils.MyX509TrustManager;
import net.sf.json.JSONObject;

public class wxUtils {
	
	/**
	 * appid、appsecret
	 * 在公众号中直接拿到的信息
	 */
	String appid ="wx33090a711ff23423";
	String appsecret="7bde1203699c33566800base35fg567";
	/**
	 * 获取微信公众号的access_token
	 */
	@Test
	public  void getAccessToken() {
		
		String URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid
		+"&secret="+appsecret;

		JSONObject jsonObject = httpRequest(URL, "GET", null);  
		try {
			if(jsonObject.getString("errcode")!=null){
				
			}
		}catch (Exception e) {
		}
		 
		 String access_token=jsonObject.getString("access_token");
		
	}

	
	public  JSONObject httpRequest(String requestUrl, String requestMethod, 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对象中得到SSLSocketFactory对象
			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(requestMethod);
 
			if ("GET".equalsIgnoreCase(requestMethod))
				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) {
		} catch (Exception e) {
		}
		return jsonObject;
	}

}






package com.common.weixin.utils;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
mport javax.net.ssl.X509TrustManager;
/**
 * 微信请求--信息管理器
 * @author m
 *
 */
public class MyX509TrustManager implements X509TrustManager{

	public MyX509TrustManager() {
		// TODO Auto-generated constructor stub
	}
	  @Override
	    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
	    }
	    @Override
	    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
	    }
	    @Override
	    public X509Certificate[] getAcceptedIssuers() {
	    //        return new X509Certificate[0];
	        return  null;
	    }

}

maven依赖


      
		    net.sf.json-lib     
		    json-lib      
		    2.4  
		     jdk15        
		   
	    
				junit
				junit
				4.11
		

你可能感兴趣的:(公众号)