HttpsClient.java 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. package com.happy.common.http;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.google.gson.Gson;
  4. import com.google.gson.reflect.TypeToken;
  5. import com.happy.Model.Message;
  6. import com.happy.Model.Visitor;
  7. import com.happy.common.wx.WxConfig;
  8. import com.happy.common.wx.WxConstants;
  9. import com.happy.common.wx.WxUtil;
  10. import com.happy.unitil.CreateSign1;
  11. import org.apache.commons.lang3.StringUtils;
  12. import org.apache.http.HttpEntity;
  13. import org.apache.http.NameValuePair;
  14. import org.apache.http.client.ClientProtocolException;
  15. import org.apache.http.client.config.RequestConfig;
  16. import org.apache.http.client.entity.UrlEncodedFormEntity;
  17. import org.apache.http.client.methods.CloseableHttpResponse;
  18. import org.apache.http.client.methods.HttpGet;
  19. import org.apache.http.client.methods.HttpPost;
  20. import org.apache.http.impl.client.CloseableHttpClient;
  21. import org.apache.http.impl.client.HttpClients;
  22. import org.apache.http.message.BasicNameValuePair;
  23. import org.apache.http.util.EntityUtils;
  24. import javax.net.ssl.HttpsURLConnection;
  25. import javax.net.ssl.SSLContext;
  26. import javax.net.ssl.SSLSocketFactory;
  27. import javax.net.ssl.TrustManager;
  28. import java.io.*;
  29. import java.net.HttpURLConnection;
  30. import java.net.URL;
  31. import java.net.URLConnection;
  32. import java.text.SimpleDateFormat;
  33. import java.util.*;
  34. /**
  35. * HttpsClient类
  36. * @author lujunjie
  37. * @date 2018/03/01
  38. */
  39. public class HttpsClient {
  40. /**
  41. * GET请求方式
  42. */
  43. public static final String METHOD_GET = "GET";
  44. /**
  45. * POST请求方式
  46. */
  47. public static final String METHOD_POST = "POST";
  48. /**
  49. * 连接超时时间
  50. */
  51. private static Integer CONNECTION_TIMEOUT = WxConfig.connectionTimeout;
  52. /**
  53. * 请求超时时间
  54. */
  55. private static Integer READ_TIMEOUT = WxConfig.readTimeout;
  56. /**
  57. * 发起https请求
  58. *
  59. * @param requestUrl 请求地址
  60. * @param requestMethod 请求方式(Get或者post)
  61. * @param postData 提交数据
  62. * @return JSONObject
  63. */
  64. public static JSONObject httpsRequestReturnJSONObject(String requestUrl, String requestMethod, String postData) throws Exception {
  65. JSONObject jsonObject = JSONObject.parseObject(HttpsClient.httpsRequestReturnString(requestUrl, requestMethod, postData));
  66. System.out.println("jsonObjectDate: " + jsonObject);
  67. return jsonObject;
  68. }
  69. /**
  70. * 发起https请求
  71. *
  72. * @param requestUrl 请求地址
  73. * @param requestMethod 请求方式(Get或者post)
  74. * @param postData 提交数据
  75. * @return String
  76. */
  77. public static String httpsRequestReturnString(String requestUrl, String requestMethod, String postData) throws Exception {
  78. String response;
  79. HttpsURLConnection httpsUrlConnection = null;
  80. try {
  81. //创建https请求证书
  82. TrustManager[] tm = {new MyX509TrustManager()};
  83. //创建SSLContext管理器对像,使用我们指定的信任管理器初始化
  84. SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
  85. sslContext.init(null, tm, new java.security.SecureRandom());
  86. SSLSocketFactory ssf = sslContext.getSocketFactory();
  87. // 创建URL对象
  88. URL url = new URL(requestUrl);
  89. // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
  90. httpsUrlConnection = (HttpsURLConnection) url.openConnection();
  91. //设置ssl证书
  92. httpsUrlConnection.setSSLSocketFactory(ssf);
  93. //设置header信息
  94. httpsUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  95. //设置User-Agent信息
  96. 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");
  97. //设置可接受信息
  98. httpsUrlConnection.setDoOutput(true);
  99. //设置可输入信息
  100. httpsUrlConnection.setDoInput(true);
  101. //不使用缓存
  102. httpsUrlConnection.setUseCaches(false);
  103. //设置请求方式(GET/POST)
  104. httpsUrlConnection.setRequestMethod(requestMethod);
  105. //设置连接超时时间
  106. if (CONNECTION_TIMEOUT > 0) {
  107. httpsUrlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
  108. } else {
  109. //默认10秒超时
  110. httpsUrlConnection.setConnectTimeout(10000);
  111. }
  112. //设置请求超时
  113. if (READ_TIMEOUT > 0) {
  114. httpsUrlConnection.setReadTimeout(READ_TIMEOUT);
  115. } else {
  116. //默认10秒超时
  117. httpsUrlConnection.setReadTimeout(10000);
  118. }
  119. //设置编码
  120. httpsUrlConnection.setRequestProperty("Charsert", WxConstants.DEFAULT_CHARSET);
  121. //判断是否需要提交数据
  122. if (StringUtils.equals(requestMethod, HttpsClient.METHOD_POST) && StringUtils.isNotBlank(postData)) {
  123. //讲参数转换为字节提交
  124. byte[] bytes = postData.getBytes(WxConstants.DEFAULT_CHARSET);
  125. //设置头信息
  126. httpsUrlConnection.setRequestProperty("Content-Length", Integer.toString(bytes.length));
  127. //开始连接
  128. httpsUrlConnection.connect();
  129. //防止中文乱码
  130. OutputStream outputStream = httpsUrlConnection.getOutputStream();
  131. outputStream.write(postData.getBytes(WxConstants.DEFAULT_CHARSET));
  132. outputStream.flush();
  133. outputStream.close();
  134. } else {
  135. //开始连接
  136. httpsUrlConnection.connect();
  137. }
  138. response = WxUtil.getStreamString(httpsUrlConnection.getInputStream());
  139. } catch (Exception e) {
  140. throw new Exception();
  141. } finally {
  142. if (httpsUrlConnection != null) {
  143. // 关闭连接
  144. httpsUrlConnection.disconnect();
  145. }
  146. }
  147. return response;
  148. }
  149. public static void get(String url, Map<String, String> params) {
  150. CloseableHttpClient httpClient = null;
  151. HttpGet httpGet = null;
  152. try {
  153. httpClient = HttpClients.createDefault();
  154. RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
  155. String ps = "";
  156. for (String pKey : params.keySet()) {
  157. if (!"".equals(ps)) {
  158. ps = ps + "&";
  159. }
  160. ps = pKey + "=" + params.get(pKey);
  161. }
  162. if (!"".equals(ps)) {
  163. url = url + "?" + ps;
  164. }
  165. httpGet = new HttpGet(url);
  166. httpGet.setConfig(requestConfig);
  167. CloseableHttpResponse response = httpClient.execute(httpGet);
  168. HttpEntity httpEntity = response.getEntity();
  169. System.out.println(EntityUtils.toString(httpEntity, "utf-8"));
  170. } catch (ClientProtocolException e) {
  171. e.printStackTrace();
  172. } catch (IOException e) {
  173. e.printStackTrace();
  174. } finally {
  175. try {
  176. if (httpGet != null) {
  177. httpGet.releaseConnection();
  178. }
  179. if (httpClient != null) {
  180. httpClient.close();
  181. }
  182. } catch (IOException e) {
  183. e.printStackTrace();
  184. }
  185. }
  186. }
  187. public static String get(String strURL) throws Exception {
  188. URL url = new URL(strURL);
  189. HttpURLConnection httpConn = (HttpURLConnection)
  190. url.openConnection();
  191. httpConn.setRequestMethod("GET");
  192. httpConn.connect();
  193. System.out.println("bbb: " + httpConn.getResponseCode());
  194. BufferedReader reader = new BufferedReader(new InputStreamReader(
  195. httpConn.getInputStream(), "utf-8"));
  196. String line;
  197. StringBuffer buffer = new StringBuffer();
  198. while ((line = reader.readLine()) != null) {
  199. buffer.append(line);
  200. }
  201. reader.close();
  202. httpConn.disconnect();
  203. return buffer.toString();
  204. }
  205. /**
  206. * 发送 post请求
  207. *
  208. * @param
  209. * @param
  210. */
  211. public static void post(String url, Map<String, String> params) {
  212. CloseableHttpClient httpClient = null;
  213. HttpPost httpPost = null;
  214. try {
  215. httpClient = HttpClients.createDefault();
  216. RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
  217. httpPost = new HttpPost(url);
  218. httpPost.setConfig(requestConfig);
  219. List<NameValuePair> ps = new ArrayList<NameValuePair>();
  220. for (String pKey : params.keySet()) {
  221. ps.add(new BasicNameValuePair(pKey, params.get(pKey)));
  222. }
  223. httpPost.setEntity(new UrlEncodedFormEntity(ps));
  224. CloseableHttpResponse response = httpClient.execute(httpPost);
  225. HttpEntity httpEntity = response.getEntity();
  226. System.out.println(EntityUtils.toString(httpEntity, "utf-8"));
  227. } catch (ClientProtocolException e) {
  228. e.printStackTrace();
  229. } catch (IOException e) {
  230. e.printStackTrace();
  231. } finally {
  232. try {
  233. if (httpPost != null) {
  234. httpPost.releaseConnection();
  235. }
  236. if (httpClient != null) {
  237. httpClient.close();
  238. }
  239. } catch (IOException e) {
  240. e.printStackTrace();
  241. }
  242. }
  243. }
  244. //url表示请求链接,param表示json格式的请求参数 //自定义菜单创建访问方式
  245. public static String sendPost(String url, String param) {
  246. PrintWriter out = null;
  247. BufferedReader in = null;
  248. String result = "";
  249. try {
  250. URL realUrl = new URL(url);
  251. // 打开和URL之间的连接
  252. URLConnection conn = realUrl.openConnection();
  253. // 设置通用的请求属性 注意Authorization生成
  254. // conn.setRequestProperty("Content-Type",
  255. // "application/x-www-form-urlencoded");
  256. // 发送POST请求必须设置如下两行
  257. conn.setDoOutput(true);
  258. conn.setDoInput(true);
  259. // 获取URLConnection对象对应的输出流
  260. out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
  261. // 发送请求参数
  262. out.print("&" + param);
  263. // flush输出流的缓冲
  264. out.flush();
  265. // 定义BufferedReader输入流来读取URL的响应
  266. in = new BufferedReader(
  267. new InputStreamReader(conn.getInputStream(), "utf-8"));
  268. String line;
  269. while ((line = in.readLine()) != null) {
  270. result += line;
  271. }
  272. } catch (Exception e) {
  273. System.out.println("发送 请求出现异常!" + e);
  274. e.printStackTrace();
  275. }
  276. // 使用finally块来关闭输出流、输入流
  277. finally {
  278. try {
  279. if (out != null) {
  280. out.close();
  281. }
  282. if (in != null) {
  283. in.close();
  284. }
  285. } catch (IOException ex) {
  286. ex.printStackTrace();
  287. }
  288. }
  289. return result;
  290. }
  291. //url表示请求链接,param表示json格式的请求参数 //自定义菜单创建访问方式
  292. public static String sendPost2(String url, String param) {
  293. PrintWriter out = null;
  294. BufferedReader in = null;
  295. String result = "";
  296. try {
  297. HttpsURLConnection httpsUrlConnection = null;
  298. //创建https请求证书
  299. TrustManager[] tm = {new MyX509TrustManager()};
  300. //创建SSLContext管理器对像,使用我们指定的信任管理器初始化
  301. SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
  302. sslContext.init(null, tm, new java.security.SecureRandom());
  303. SSLSocketFactory ssf = sslContext.getSocketFactory();
  304. // 创建URL对象
  305. URL realUrl = new URL(url);
  306. // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象,
  307. // 打开和URL之间的连接
  308. httpsUrlConnection = (HttpsURLConnection) realUrl.openConnection();
  309. //设置ssl证书
  310. httpsUrlConnection.setSSLSocketFactory(ssf);
  311. // 设置通用的请求属性 注意Authorization生成
  312. // conn.setRequestProperty("Content-Type",
  313. // "application/x-www-form-urlencoded");
  314. // 发送POST请求必须设置如下两行
  315. httpsUrlConnection.setRequestMethod("POST");
  316. httpsUrlConnection.setDoOutput(true);
  317. httpsUrlConnection.setDoInput(true);
  318. // 获取URLConnection对象对应的输出流
  319. out = new PrintWriter(new OutputStreamWriter(httpsUrlConnection.getOutputStream(), "utf-8"));
  320. // 发送请求参数
  321. out.print("&" + param);
  322. // flush输出流的缓冲
  323. out.flush();
  324. if (httpsUrlConnection.getResponseCode() == 200) {
  325. // 定义BufferedReader输入流来读取URL的响应
  326. in = new BufferedReader(
  327. new InputStreamReader(httpsUrlConnection.getInputStream(), "utf-8"));
  328. String line;
  329. while ((line = in.readLine()) != null) {
  330. result += line;
  331. }
  332. } else {
  333. result = "获取输入流异常!";
  334. }
  335. } catch (Exception e) {
  336. System.out.println("发送 请求出现异常!" + e);
  337. e.printStackTrace();
  338. }
  339. // 使用finally块来关闭输出流、输入流
  340. finally {
  341. try {
  342. if (out != null) {
  343. out.close();
  344. }
  345. if (in != null) {
  346. in.close();
  347. }
  348. } catch (IOException ex) {
  349. ex.printStackTrace();
  350. }
  351. }
  352. return result;
  353. }
  354. public static String sendPost3(String url, String param) {
  355. PrintWriter out = null;
  356. BufferedReader in = null;
  357. String result = "";
  358. try {
  359. URL realUrl = new URL(url);
  360. // 打开和URL之间的连接
  361. URLConnection conn = realUrl.openConnection();
  362. // 设置通用的请求属性 注意Authorization生成
  363. // conn.setRequestProperty("Content-Type",
  364. // "application/x-www-form-urlencoded");
  365. // 发送POST请求必须设置如下两行
  366. conn.setDoOutput(true);
  367. conn.setDoInput(true);
  368. // 获取URLConnection对象对应的输出流
  369. out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
  370. // 发送请求参数
  371. out.print(param);
  372. // flush输出流的缓冲
  373. out.flush();
  374. // 定义BufferedReader输入流来读取URL的响应
  375. in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
  376. String line;
  377. while ((line = in.readLine()) != null) {
  378. result += line;
  379. }
  380. } catch (Exception e) {
  381. System.out.println("发送 POST 请求出现异常!" + e);
  382. e.printStackTrace();
  383. }
  384. // 使用finally块来关闭输出流、输入流
  385. finally {
  386. try {
  387. if (out != null) {
  388. out.close();
  389. }
  390. if (in != null) {
  391. in.close();
  392. }
  393. } catch (IOException ex) {
  394. ex.printStackTrace();
  395. }
  396. }
  397. return result;
  398. }
  399. public static String sendJson(String request_url, JSONObject json) {
  400. OutputStreamWriter out = null;
  401. InputStream is = null;
  402. String result = "";
  403. try {
  404. URL url = new URL(request_url);// 创建连接
  405. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  406. connection.setDoOutput(true);
  407. connection.setDoInput(true);
  408. connection.setUseCaches(false);
  409. connection.setInstanceFollowRedirects(true);
  410. connection.setRequestMethod("POST"); // 设置请求方式
  411. // 设置接收数据的格式
  412. connection.setRequestProperty("Accept", "application/json");
  413. // 设置发送数据的格式
  414. connection.setRequestProperty("Content-Type", "application/json");
  415. connection.connect();
  416. out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
  417. out.append(json.toString());
  418. out.flush();
  419. out.close();
  420. // 读取响应
  421. is = connection.getInputStream();
  422. int length = (int) connection.getContentLength();// 获取长度
  423. if (length != -1) {
  424. byte[] data = new byte[length];
  425. byte[] temp = new byte[512];
  426. int readLen = 0;
  427. int destPos = 0;
  428. while ((readLen = is.read(temp)) > 0) {
  429. System.arraycopy(temp, 0, data, destPos, readLen);
  430. destPos += readLen;
  431. }
  432. result = new String(data, "UTF-8"); // utf-8编码
  433. System.out.println("主机返回:" + result);
  434. }
  435. } catch (IOException e) {
  436. e.printStackTrace();
  437. } finally {
  438. try {
  439. is.close();
  440. out.close();
  441. } catch (IOException e) {
  442. e.printStackTrace();
  443. }
  444. }
  445. return result;
  446. }
  447. public static String sendJson2(String request_url, JSONObject json) {
  448. OutputStreamWriter out = null;
  449. InputStream is = null;
  450. String result = "";
  451. try {
  452. URL url = new URL(request_url);// 创建连接
  453. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  454. connection.setDoOutput(true);
  455. connection.setDoInput(true);
  456. connection.setUseCaches(false);
  457. connection.setInstanceFollowRedirects(true);
  458. connection.setRequestMethod("POST"); // 设置请求方式
  459. // 设置接收数据的格式
  460. connection.setRequestProperty("Accept", "application/json");
  461. // 设置发送数据的格式
  462. connection.setRequestProperty("Content-Type", "application/json");
  463. connection.connect();
  464. out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
  465. out.append(json.toString());
  466. out.flush();
  467. out.close();
  468. // 读取响应
  469. is = connection.getInputStream();
  470. BufferedReader in = new BufferedReader(new InputStreamReader(is));
  471. result = in.readLine();
  472. } catch (IOException e) {
  473. e.printStackTrace();
  474. } finally {
  475. try {
  476. is.close();
  477. out.close();
  478. } catch (IOException e) {
  479. e.printStackTrace();
  480. }
  481. }
  482. return result;
  483. }
  484. // public static void main(String[] args) throws Exception {
  485. // JSONObject json = new JSONObject();
  486. // String ukey = "6VMZEC5C6HZM7EO8";
  487. // JSONObject datas = new JSONObject();
  488. // datas.put("car_number", "赣555555");
  489. // datas.put("begin_time", 1630800000);
  490. // datas.put("end_time", 1630918800);
  491. // datas.put("mobile", "15399990000");
  492. // // 生成带签名的字符串并使用MD5生成签名,然后转大写
  493. // String sign = datas.toJSONString()+"key="+ukey;
  494. // sign = CreateSign1.MD5(sign).toUpperCase();
  495. // json.put("service_name", "visitor_sync");
  496. // json.put("sign", sign);
  497. // json.put("park_id", "10033845");
  498. // json.put("data", datas);
  499. // String msg = sendJson2("http://istparking.sciseetech.com/public/visitor/do", json);
  500. // System.out.println(msg);
  501. // }
  502. // public static void main(String[] args) {
  503. // JSONObject json = new JSONObject();
  504. // String ukey = "6VMZEC5C6HZM7EO8";
  505. // JSONObject datas = new JSONObject();
  506. // // 1新增 2编辑 3删除
  507. // datas.put("operate_type", "1");
  508. // // 白名单编号(收费系统唯一编号)
  509. // datas.put("card_id", "20210810556");
  510. // datas.put("car_number", "冀A111118");
  511. // datas.put("mobile", "15399990000");
  512. // // 是否长期类型1是,0否,默认0
  513. // datas.put("end_type", "0");
  514. // datas.put("b_time", 1630800000);
  515. // datas.put("e_time", 1630918800);
  516. // // 生成带签名的字符串并使用MD5生成签名,然后转大写
  517. // String sign = datas.toJSONString()+"key="+ukey;
  518. // sign = CreateSign1.MD5(sign).toUpperCase();
  519. // json.put("service_name", "white_vip");
  520. // json.put("sign", sign);
  521. // json.put("park_id", "10033845");
  522. // json.put("data", datas);
  523. // String msg = sendJson2("http://istparking.sciseetech.com/public/vip/white", json);
  524. // Gson gson=new Gson();
  525. // HashMap<String, String> userMoney = gson.fromJson(msg.toString(), new TypeToken<HashMap<String, String>>(){}.getType());
  526. // System.out.println(msg);
  527. // }
  528. // public static void main(String[] args) throws Exception {
  529. // JSONObject data = new JSONObject();
  530. // data.put("carNumber", "赣555555");
  531. // data.put("parkId", "10033845");
  532. // data.put("type", "2"); // 进出类别 1进、2出
  533. // data.put("recordTime", "2021-11-10 17:02:25");
  534. // String msg = sendJson2("https://chtech.ncjti.edu.cn/bigdata-api/api/intoAndOut/carIntoAndOutRecordUpload", data);
  535. // System.out.println(msg);
  536. // }
  537. public static void main(String[] args) {
  538. String msg = HttpsClient.sendPost(
  539. "https://open.wecard.qq.com/cgi-bin/oauth2/token?app_key="+
  540. "48103AB41FFBC5FE&app_secret=5B7FB4D3CC243695EED3693044D0FC54&grant_type=client_credentials&scope=base&ocode=1015730314", "");
  541. Gson gson=new Gson();
  542. HashMap<String, String> userMap = gson.fromJson(msg.toString(), new TypeToken<HashMap<String, String>>(){}.getType());
  543. String token = userMap.get("access_token");
  544. System.out.println(token);
  545. JSONObject data = new JSONObject();
  546. ArrayList<String> as = new ArrayList<>();
  547. as.add("REG4377000007");
  548. String json = JSONObject.toJSONString(as);
  549. data.put("cards", json);
  550. data.put("title", "访客预约结果");
  551. data.put("content", "预约成功"); // 进出类别 1进、2出
  552. data.put("sender", "保卫处");
  553. String msg2 = sendJson2("https://open.wecard.qq.com/cgi-bin/notice/send?access_token="+token, data);
  554. System.out.println(msg2);
  555. }
  556. }