package com.meeting.utils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
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 net.sf.json.JSONObject;
/**
*
* @ClassName: CommonUtil
* @Description: 通用工具类
* @author chengrui
* @date 2017-3-28 上午9:33:01
*/
public class CommonUtil {
/**
*
* @Title: httpsRequest
* @Description: 发送请求,返回JSONObject对象
* @param requestUrl
* @param requestMethod
* @param outputStr
* @return
*/
public static JSONObject httpsRequest(String requestUrl,
String requestMethod, String outputStr) {
JSONObject jsonObject = null;
try {
// 使用自定义的信任管理器
TrustManager[] tm = { new MyX509TrustManagerUtil() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
// 建立连接
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
// 设置请求方式
conn.setRequestMethod(requestMethod);
// 当outputStr不为null时,向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 获取输入流
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
// 读取响应内容
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 关闭资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
conn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (Exception e) {
System.out.println("ERROR");
}
return jsonObject;
}
}
通用工具类
最新推荐文章于 2024-01-22 16:46:14 发布