HTTPS请求工具类汇总
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
HTTPS请求
package com.sunzk.dreamsunlight.weixin.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import .ConnectException;
import .URL;
import .ssl.HttpsURLConnection; import .ssl.SSLContext;
import .ssl.SSLSocketFactory; import .ssl.TrustManager;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import
com.sunzk.dreamsunlight.weixin.certificate.MyX509 TrustManager;
import com.sunzk.dreamsunlight.weixin.model.Menu; import
com.sunzk.dreamsunlight.weixin.token.AccessToken;
/**
*
* @ClassName: WeiXinHttpsUtil
*
* @Description: TODO(微信HTTPS请求工具类)
*
* @author sunzk-dreamsunlight-QQ(1131341075)
*
* @date 2016-11-14 上午10:05:56
*
*/
public class WeiXinHttpsUtil {
private static Logger logger =
Logger.getLogger(WeiXinHttpsUtil.class);
// 获取access_token的接口地址(GET)限200(次/天)
public final static String access_token_url = "https:///cgi-bin/token?grant_ty pe=client_credential&appid=APPID&secret=APPSECRET ";
/**
* 发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static 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();
// 注意编码格式,防止中文乱码