HttpsClient.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. package com.happy.common.http;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.happy.common.wx.WxConfig;
  4. import com.happy.common.wx.WxConstants;
  5. import com.happy.common.wx.WxUtil;
  6. import org.apache.commons.lang3.StringUtils;
  7. import org.apache.http.HttpEntity;
  8. import org.apache.http.NameValuePair;
  9. import org.apache.http.client.ClientProtocolException;
  10. import org.apache.http.client.config.RequestConfig;
  11. import org.apache.http.client.entity.UrlEncodedFormEntity;
  12. import org.apache.http.client.methods.CloseableHttpResponse;
  13. import org.apache.http.client.methods.HttpGet;
  14. import org.apache.http.client.methods.HttpPost;
  15. import org.apache.http.impl.client.CloseableHttpClient;
  16. import org.apache.http.impl.client.HttpClients;
  17. import org.apache.http.message.BasicNameValuePair;
  18. import org.apache.http.util.EntityUtils;
  19. import javax.net.ssl.HttpsURLConnection;
  20. import javax.net.ssl.SSLContext;
  21. import javax.net.ssl.SSLSocketFactory;
  22. import javax.net.ssl.TrustManager;
  23. import java.io.*;
  24. import java.net.HttpURLConnection;
  25. import java.net.URL;
  26. import java.net.URLConnection;
  27. import java.util.ArrayList;
  28. import java.util.HashMap;
  29. import java.util.List;
  30. import java.util.Map;
  31. /**
  32. * HttpsClient类
  33. * @author lujunjie
  34. * @date 2018/03/01
  35. */
  36. public class HttpsClient {
  37. /**
  38. * GET请求方式
  39. */
  40. public static final String METHOD_GET = "GET";
  41. /**
  42. * POST请求方式
  43. */
  44. public static final String METHOD_POST = "POST";
  45. /**
  46. * 连接超时时间
  47. */
  48. private static Integer CONNECTION_TIMEOUT = WxConfig.connectionTimeout;
  49. /**
  50. * 请求超时时间
  51. */
  52. private static Integer READ_TIMEOUT = WxConfig.readTimeout;
  53. /**
  54. * 发起https请求
  55. * @param requestUrl 请求地址
  56. * @param requestMethod 请求方式(Get或者post)
  57. * @param postData 提交数据
  58. * @return JSONObject
  59. */
  60. public static JSONObject httpsRequestReturnJSONObject(String requestUrl, String requestMethod, String postData) throws Exception{
  61. JSONObject jsonObject = JSONObject.parseObject(HttpsClient.httpsRequestReturnString(requestUrl,requestMethod,postData));
  62. System.out.println("jsonObjectDate: " + jsonObject);
  63. return jsonObject;
  64. }
  65. /**
  66. * 发起https请求
  67. * @param requestUrl 请求地址
  68. * @param requestMethod 请求方式(Get或者post)
  69. * @param postData 提交数据
  70. * @return String
  71. */
  72. public static String httpsRequestReturnString(String requestUrl, String requestMethod, String postData) throws Exception{
  73. String response;
  74. HttpsURLConnection httpsUrlConnection = null;
  75. try{
  76. //创建https请求证书
  77. TrustManager[] tm={new MyX509TrustManager()};
  78. //创建SSLContext管理器对像,使用我们指定的信任管理器初始化
  79. SSLContext sslContext=SSLContext.getInstance("SSL","SunJSSE");
  80. sslContext.init(null, tm, new java.security.SecureRandom());
  81. SSLSocketFactory ssf=sslContext.getSocketFactory();
  82. // 创建URL对象
  83. URL url= new URL(requestUrl);
  84. // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
  85. httpsUrlConnection=(HttpsURLConnection)url.openConnection();
  86. //设置ssl证书
  87. httpsUrlConnection.setSSLSocketFactory(ssf);
  88. //设置header信息
  89. httpsUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  90. //设置User-Agent信息
  91. httpsUrlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
  92. //设置可接受信息
  93. httpsUrlConnection.setDoOutput(true);
  94. //设置可输入信息
  95. httpsUrlConnection.setDoInput(true);
  96. //不使用缓存
  97. httpsUrlConnection.setUseCaches(false);
  98. //设置请求方式(GET/POST)
  99. httpsUrlConnection.setRequestMethod(requestMethod);
  100. //设置连接超时时间
  101. if (CONNECTION_TIMEOUT > 0) {
  102. httpsUrlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
  103. } else {
  104. //默认10秒超时
  105. httpsUrlConnection.setConnectTimeout(10000);
  106. }
  107. //设置请求超时
  108. if (READ_TIMEOUT > 0) {
  109. httpsUrlConnection.setReadTimeout(READ_TIMEOUT);
  110. } else {
  111. //默认10秒超时
  112. httpsUrlConnection.setReadTimeout(10000);
  113. }
  114. //设置编码
  115. httpsUrlConnection.setRequestProperty("Charsert", WxConstants.DEFAULT_CHARSET);
  116. //判断是否需要提交数据
  117. if(StringUtils.equals(requestMethod,HttpsClient.METHOD_POST) && StringUtils.isNotBlank(postData)){
  118. //讲参数转换为字节提交
  119. byte[] bytes = postData.getBytes(WxConstants.DEFAULT_CHARSET);
  120. //设置头信息
  121. httpsUrlConnection.setRequestProperty("Content-Length", Integer.toString(bytes.length));
  122. //开始连接
  123. httpsUrlConnection.connect();
  124. //防止中文乱码
  125. OutputStream outputStream=httpsUrlConnection.getOutputStream();
  126. outputStream.write(postData.getBytes(WxConstants.DEFAULT_CHARSET));
  127. outputStream.flush();
  128. outputStream.close();
  129. }else{
  130. //开始连接
  131. httpsUrlConnection.connect();
  132. }
  133. response = WxUtil.getStreamString(httpsUrlConnection.getInputStream());
  134. }catch (Exception e){
  135. throw new Exception();
  136. }finally {
  137. if (httpsUrlConnection != null) {
  138. // 关闭连接
  139. httpsUrlConnection.disconnect();
  140. }
  141. }
  142. return response;
  143. }
  144. public static void get(String url, Map<String, String> params){
  145. CloseableHttpClient httpClient = null;
  146. HttpGet httpGet = null;
  147. try {
  148. httpClient = HttpClients.createDefault();
  149. RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
  150. String ps = "";
  151. for (String pKey : params.keySet()) {
  152. if(!"".equals(ps)){
  153. ps = ps + "&";
  154. }
  155. ps = pKey+"="+params.get(pKey);
  156. }
  157. if(!"".equals(ps)){
  158. url = url + "?" + ps;
  159. }
  160. httpGet = new HttpGet(url);
  161. httpGet.setConfig(requestConfig);
  162. CloseableHttpResponse response = httpClient.execute(httpGet);
  163. HttpEntity httpEntity = response.getEntity();
  164. System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
  165. } catch (ClientProtocolException e) {
  166. e.printStackTrace();
  167. } catch (IOException e) {
  168. e.printStackTrace();
  169. }finally{
  170. try {
  171. if(httpGet!=null){
  172. httpGet.releaseConnection();
  173. }
  174. if(httpClient!=null){
  175. httpClient.close();
  176. }
  177. } catch (IOException e) {
  178. e.printStackTrace();
  179. }
  180. }
  181. }
  182. public static String get(String strURL) throws Exception{
  183. URL url = new URL(strURL);
  184. HttpURLConnection httpConn = (HttpURLConnection)
  185. url.openConnection();
  186. httpConn.setRequestMethod("GET");
  187. httpConn.connect();
  188. System.out.println("bbb: "+httpConn.getResponseCode());
  189. BufferedReader reader = new BufferedReader(new InputStreamReader(
  190. httpConn.getInputStream(),"utf-8"));
  191. String line;
  192. StringBuffer buffer = new StringBuffer();
  193. while ((line = reader.readLine()) != null) {
  194. buffer.append(line);
  195. }
  196. reader.close();
  197. httpConn.disconnect();
  198. return buffer.toString();
  199. }
  200. /**
  201. * 发送 post请求
  202. * @param
  203. * @param
  204. */
  205. public static void post(String url, Map<String, String> params){
  206. CloseableHttpClient httpClient = null;
  207. HttpPost httpPost = null;
  208. try {
  209. httpClient = HttpClients.createDefault();
  210. RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
  211. httpPost = new HttpPost(url);
  212. httpPost.setConfig(requestConfig);
  213. List<NameValuePair> ps = new ArrayList<NameValuePair>();
  214. for (String pKey : params.keySet()) {
  215. ps.add(new BasicNameValuePair(pKey, params.get(pKey)));
  216. }
  217. httpPost.setEntity(new UrlEncodedFormEntity(ps));
  218. CloseableHttpResponse response = httpClient.execute(httpPost);
  219. HttpEntity httpEntity = response.getEntity();
  220. System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
  221. } catch (ClientProtocolException e) {
  222. e.printStackTrace();
  223. } catch (IOException e) {
  224. e.printStackTrace();
  225. }finally{
  226. try {
  227. if(httpPost!=null){
  228. httpPost.releaseConnection();
  229. }
  230. if(httpClient!=null){
  231. httpClient.close();
  232. }
  233. } catch (IOException e) {
  234. e.printStackTrace();
  235. }
  236. }
  237. }
  238. //url表示请求链接,param表示json格式的请求参数 //自定义菜单创建访问方式
  239. public static String sendPost(String url, String param) {
  240. PrintWriter out = null;
  241. BufferedReader in = null;
  242. String result = "";
  243. try {
  244. URL realUrl = new URL(url);
  245. // 打开和URL之间的连接
  246. URLConnection conn = realUrl.openConnection();
  247. // 设置通用的请求属性 注意Authorization生成
  248. // conn.setRequestProperty("Content-Type",
  249. // "application/x-www-form-urlencoded");
  250. // 发送POST请求必须设置如下两行
  251. conn.setDoOutput(true);
  252. conn.setDoInput(true);
  253. // 获取URLConnection对象对应的输出流
  254. out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
  255. // 发送请求参数
  256. out.print("&"+param);
  257. // flush输出流的缓冲
  258. out.flush();
  259. // 定义BufferedReader输入流来读取URL的响应
  260. in = new BufferedReader(
  261. new InputStreamReader(conn.getInputStream(),"utf-8"));
  262. String line;
  263. while ((line = in.readLine()) != null) {
  264. result += line;
  265. }
  266. } catch (Exception e) {
  267. System.out.println("发送 请求出现异常!" + e);
  268. e.printStackTrace();
  269. }
  270. // 使用finally块来关闭输出流、输入流
  271. finally {
  272. try {
  273. if (out != null) {
  274. out.close();
  275. }
  276. if (in != null) {
  277. in.close();
  278. }
  279. } catch (IOException ex) {
  280. ex.printStackTrace();
  281. }
  282. }
  283. return result;
  284. }
  285. //url表示请求链接,param表示json格式的请求参数 //自定义菜单创建访问方式
  286. public static String sendPost2(String url, String param) {
  287. PrintWriter out = null;
  288. BufferedReader in = null;
  289. String result = "";
  290. try {
  291. HttpsURLConnection httpsUrlConnection = null;
  292. //创建https请求证书
  293. TrustManager[] tm={new MyX509TrustManager()};
  294. //创建SSLContext管理器对像,使用我们指定的信任管理器初始化
  295. SSLContext sslContext=SSLContext.getInstance("SSL","SunJSSE");
  296. sslContext.init(null, tm, new java.security.SecureRandom());
  297. SSLSocketFactory ssf=sslContext.getSocketFactory();
  298. // 创建URL对象
  299. URL realUrl= new URL(url);
  300. // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象,
  301. // 打开和URL之间的连接
  302. httpsUrlConnection=(HttpsURLConnection)realUrl.openConnection();
  303. //设置ssl证书
  304. httpsUrlConnection.setSSLSocketFactory(ssf);
  305. // 设置通用的请求属性 注意Authorization生成
  306. // conn.setRequestProperty("Content-Type",
  307. // "application/x-www-form-urlencoded");
  308. // 发送POST请求必须设置如下两行
  309. httpsUrlConnection.setRequestMethod("POST");
  310. httpsUrlConnection.setDoOutput(true);
  311. httpsUrlConnection.setDoInput(true);
  312. // 获取URLConnection对象对应的输出流
  313. out = new PrintWriter(new OutputStreamWriter(httpsUrlConnection.getOutputStream(),"utf-8"));
  314. // 发送请求参数
  315. out.print("&"+param);
  316. // flush输出流的缓冲
  317. out.flush();
  318. if (httpsUrlConnection.getResponseCode()==200) {
  319. // 定义BufferedReader输入流来读取URL的响应
  320. in = new BufferedReader(
  321. new InputStreamReader(httpsUrlConnection.getInputStream(), "utf-8"));
  322. String line;
  323. while ((line = in.readLine()) != null) {
  324. result += line;
  325. }
  326. }else {
  327. result = "获取输入流异常!";
  328. }
  329. } catch (Exception e) {
  330. System.out.println("发送 请求出现异常!" + e);
  331. e.printStackTrace();
  332. }
  333. // 使用finally块来关闭输出流、输入流
  334. finally {
  335. try {
  336. if (out != null) {
  337. out.close();
  338. }
  339. if (in != null) {
  340. in.close();
  341. }
  342. } catch (IOException ex) {
  343. ex.printStackTrace();
  344. }
  345. }
  346. return result;
  347. }
  348. public static void main(String[] args) {
  349. Map<String, String> req = new HashMap<>();
  350. req.put("operator_id", "000000002");
  351. req.put("operator_secret", "SBC88d0ItR3w6oCTY");
  352. req.put("data_secret", "Epc3hhs0imtVhPSu");
  353. req.put("data_secret_iv", "r57m1sr8Tg2E302L");
  354. req.put("sign_key", "ikAhygeGCRnEdhjgBKf");
  355. }
  356. }