HttpsClient.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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.Until.CreateSign1;
  6. import com.happy.Until.TimeExchange;
  7. import com.happy.common.wx.WxConfig;
  8. import com.happy.common.wx.WxConstants;
  9. import com.happy.common.wx.WxUtil;
  10. import org.apache.commons.lang3.StringUtils;
  11. import org.apache.http.HttpEntity;
  12. import org.apache.http.NameValuePair;
  13. import org.apache.http.client.ClientProtocolException;
  14. import org.apache.http.client.config.RequestConfig;
  15. import org.apache.http.client.entity.UrlEncodedFormEntity;
  16. import org.apache.http.client.methods.CloseableHttpResponse;
  17. import org.apache.http.client.methods.HttpGet;
  18. import org.apache.http.client.methods.HttpPost;
  19. import org.apache.http.impl.client.CloseableHttpClient;
  20. import org.apache.http.impl.client.HttpClients;
  21. import org.apache.http.message.BasicNameValuePair;
  22. import org.apache.http.util.EntityUtils;
  23. import javax.net.ssl.HttpsURLConnection;
  24. import javax.net.ssl.SSLContext;
  25. import javax.net.ssl.SSLSocketFactory;
  26. import javax.net.ssl.TrustManager;
  27. import java.io.*;
  28. import java.net.HttpURLConnection;
  29. import java.net.URL;
  30. import java.net.URLConnection;
  31. import java.text.SimpleDateFormat;
  32. import java.util.*;
  33. /**
  34. * HttpsClient类
  35. * @author lujunjie
  36. * @date 2018/03/01
  37. */
  38. public class HttpsClient {
  39. /**
  40. * GET请求方式
  41. */
  42. public static final String METHOD_GET = "GET";
  43. /**
  44. * POST请求方式
  45. */
  46. public static final String METHOD_POST = "POST";
  47. /**
  48. * 连接超时时间
  49. */
  50. private static Integer CONNECTION_TIMEOUT = WxConfig.connectionTimeout;
  51. /**
  52. * 请求超时时间
  53. */
  54. private static Integer READ_TIMEOUT = WxConfig.readTimeout;
  55. /**
  56. * 发起https请求
  57. * @param requestUrl 请求地址
  58. * @param requestMethod 请求方式(Get或者post)
  59. * @param postData 提交数据
  60. * @return JSONObject
  61. */
  62. public static JSONObject httpsRequestReturnJSONObject(String requestUrl, String requestMethod, String postData) throws Exception{
  63. JSONObject jsonObject = JSONObject.parseObject(HttpsClient.httpsRequestReturnString(requestUrl,requestMethod,postData));
  64. System.out.println("jsonObjectDate: " + jsonObject);
  65. return jsonObject;
  66. }
  67. /**
  68. * 发起https请求
  69. * @param requestUrl 请求地址
  70. * @param requestMethod 请求方式(Get或者post)
  71. * @param postData 提交数据
  72. * @return String
  73. */
  74. public static String httpsRequestReturnString(String requestUrl, String requestMethod, String postData) throws Exception{
  75. String response;
  76. HttpsURLConnection httpsUrlConnection = null;
  77. try{
  78. //创建https请求证书
  79. TrustManager[] tm={new MyX509TrustManager()};
  80. //创建SSLContext管理器对像,使用我们指定的信任管理器初始化
  81. SSLContext sslContext=SSLContext.getInstance("SSL","SunJSSE");
  82. sslContext.init(null, tm, new java.security.SecureRandom());
  83. SSLSocketFactory ssf=sslContext.getSocketFactory();
  84. // 创建URL对象
  85. URL url= new URL(requestUrl);
  86. // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
  87. httpsUrlConnection=(HttpsURLConnection)url.openConnection();
  88. //设置ssl证书
  89. httpsUrlConnection.setSSLSocketFactory(ssf);
  90. //设置header信息
  91. httpsUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  92. //设置User-Agent信息
  93. 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");
  94. //设置可接受信息
  95. httpsUrlConnection.setDoOutput(true);
  96. //设置可输入信息
  97. httpsUrlConnection.setDoInput(true);
  98. //不使用缓存
  99. httpsUrlConnection.setUseCaches(false);
  100. //设置请求方式(GET/POST)
  101. httpsUrlConnection.setRequestMethod(requestMethod);
  102. //设置连接超时时间
  103. if (CONNECTION_TIMEOUT > 0) {
  104. httpsUrlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
  105. } else {
  106. //默认10秒超时
  107. httpsUrlConnection.setConnectTimeout(10000);
  108. }
  109. //设置请求超时
  110. if (READ_TIMEOUT > 0) {
  111. httpsUrlConnection.setReadTimeout(READ_TIMEOUT);
  112. } else {
  113. //默认10秒超时
  114. httpsUrlConnection.setReadTimeout(10000);
  115. }
  116. //设置编码
  117. httpsUrlConnection.setRequestProperty("Charsert", WxConstants.DEFAULT_CHARSET);
  118. //判断是否需要提交数据
  119. if(StringUtils.equals(requestMethod,HttpsClient.METHOD_POST) && StringUtils.isNotBlank(postData)){
  120. //讲参数转换为字节提交
  121. byte[] bytes = postData.getBytes(WxConstants.DEFAULT_CHARSET);
  122. //设置头信息
  123. httpsUrlConnection.setRequestProperty("Content-Length", Integer.toString(bytes.length));
  124. //开始连接
  125. httpsUrlConnection.connect();
  126. //防止中文乱码
  127. OutputStream outputStream=httpsUrlConnection.getOutputStream();
  128. outputStream.write(postData.getBytes(WxConstants.DEFAULT_CHARSET));
  129. outputStream.flush();
  130. outputStream.close();
  131. }else{
  132. //开始连接
  133. httpsUrlConnection.connect();
  134. }
  135. response = WxUtil.getStreamString(httpsUrlConnection.getInputStream());
  136. }catch (Exception e){
  137. throw new Exception();
  138. }finally {
  139. if (httpsUrlConnection != null) {
  140. // 关闭连接
  141. httpsUrlConnection.disconnect();
  142. }
  143. }
  144. return response;
  145. }
  146. public static void get(String url, Map<String, String> params){
  147. CloseableHttpClient httpClient = null;
  148. HttpGet httpGet = null;
  149. try {
  150. httpClient = HttpClients.createDefault();
  151. RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
  152. String ps = "";
  153. for (String pKey : params.keySet()) {
  154. if(!"".equals(ps)){
  155. ps = ps + "&";
  156. }
  157. ps = pKey+"="+params.get(pKey);
  158. }
  159. if(!"".equals(ps)){
  160. url = url + "?" + ps;
  161. }
  162. httpGet = new HttpGet(url);
  163. httpGet.setConfig(requestConfig);
  164. CloseableHttpResponse response = httpClient.execute(httpGet);
  165. HttpEntity httpEntity = response.getEntity();
  166. System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
  167. } catch (ClientProtocolException e) {
  168. e.printStackTrace();
  169. } catch (IOException e) {
  170. e.printStackTrace();
  171. }finally{
  172. try {
  173. if(httpGet!=null){
  174. httpGet.releaseConnection();
  175. }
  176. if(httpClient!=null){
  177. httpClient.close();
  178. }
  179. } catch (IOException e) {
  180. e.printStackTrace();
  181. }
  182. }
  183. }
  184. public static String get(String strURL) throws Exception{
  185. URL url = new URL(strURL);
  186. HttpURLConnection httpConn = (HttpURLConnection)
  187. url.openConnection();
  188. httpConn.setRequestMethod("GET");
  189. httpConn.connect();
  190. System.out.println("bbb: "+httpConn.getResponseCode());
  191. BufferedReader reader = new BufferedReader(new InputStreamReader(
  192. httpConn.getInputStream(),"utf-8"));
  193. String line;
  194. StringBuffer buffer = new StringBuffer();
  195. while ((line = reader.readLine()) != null) {
  196. buffer.append(line);
  197. }
  198. reader.close();
  199. httpConn.disconnect();
  200. return buffer.toString();
  201. }
  202. /**
  203. * 发送 post请求
  204. * @param
  205. * @param
  206. */
  207. public static void post(String url, Map<String, String> params){
  208. CloseableHttpClient httpClient = null;
  209. HttpPost httpPost = null;
  210. try {
  211. httpClient = HttpClients.createDefault();
  212. RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
  213. httpPost = new HttpPost(url);
  214. httpPost.setConfig(requestConfig);
  215. List<NameValuePair> ps = new ArrayList<NameValuePair>();
  216. for (String pKey : params.keySet()) {
  217. ps.add(new BasicNameValuePair(pKey, params.get(pKey)));
  218. }
  219. httpPost.setEntity(new UrlEncodedFormEntity(ps));
  220. CloseableHttpResponse response = httpClient.execute(httpPost);
  221. HttpEntity httpEntity = response.getEntity();
  222. System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
  223. } catch (ClientProtocolException e) {
  224. e.printStackTrace();
  225. } catch (IOException e) {
  226. e.printStackTrace();
  227. }finally{
  228. try {
  229. if(httpPost!=null){
  230. httpPost.releaseConnection();
  231. }
  232. if(httpClient!=null){
  233. httpClient.close();
  234. }
  235. } catch (IOException e) {
  236. e.printStackTrace();
  237. }
  238. }
  239. }
  240. //url表示请求链接,param表示json格式的请求参数 //自定义菜单创建访问方式
  241. public static String sendPost(String url, String param) {
  242. PrintWriter out = null;
  243. BufferedReader in = null;
  244. String result = "";
  245. try {
  246. URL realUrl = new URL(url);
  247. // 打开和URL之间的连接
  248. URLConnection conn = realUrl.openConnection();
  249. // 设置通用的请求属性 注意Authorization生成
  250. // conn.setRequestProperty("Content-Type",
  251. // "application/x-www-form-urlencoded");
  252. // 发送POST请求必须设置如下两行
  253. conn.setDoOutput(true);
  254. conn.setDoInput(true);
  255. // 获取URLConnection对象对应的输出流
  256. out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
  257. // 发送请求参数
  258. out.print("&"+param);
  259. // flush输出流的缓冲
  260. out.flush();
  261. // 定义BufferedReader输入流来读取URL的响应
  262. in = new BufferedReader(
  263. new InputStreamReader(conn.getInputStream(),"utf-8"));
  264. String line;
  265. while ((line = in.readLine()) != null) {
  266. result += line;
  267. }
  268. } catch (Exception e) {
  269. System.out.println("发送 请求出现异常!" + e);
  270. e.printStackTrace();
  271. }
  272. // 使用finally块来关闭输出流、输入流
  273. finally {
  274. try {
  275. if (out != null) {
  276. out.close();
  277. }
  278. if (in != null) {
  279. in.close();
  280. }
  281. } catch (IOException ex) {
  282. ex.printStackTrace();
  283. }
  284. }
  285. return result;
  286. }
  287. //url表示请求链接,param表示json格式的请求参数 //自定义菜单创建访问方式
  288. public static String sendPost2(String url, String param) {
  289. PrintWriter out = null;
  290. BufferedReader in = null;
  291. String result = "";
  292. try {
  293. HttpsURLConnection httpsUrlConnection = null;
  294. //创建https请求证书
  295. TrustManager[] tm={new MyX509TrustManager()};
  296. //创建SSLContext管理器对像,使用我们指定的信任管理器初始化
  297. SSLContext sslContext=SSLContext.getInstance("SSL","SunJSSE");
  298. sslContext.init(null, tm, new java.security.SecureRandom());
  299. SSLSocketFactory ssf=sslContext.getSocketFactory();
  300. // 创建URL对象
  301. URL realUrl= new URL(url);
  302. // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象,
  303. // 打开和URL之间的连接
  304. httpsUrlConnection=(HttpsURLConnection)realUrl.openConnection();
  305. //设置ssl证书
  306. httpsUrlConnection.setSSLSocketFactory(ssf);
  307. // 设置通用的请求属性 注意Authorization生成
  308. // conn.setRequestProperty("Content-Type",
  309. // "application/x-www-form-urlencoded");
  310. // 发送POST请求必须设置如下两行
  311. httpsUrlConnection.setRequestMethod("POST");
  312. httpsUrlConnection.setDoOutput(true);
  313. httpsUrlConnection.setDoInput(true);
  314. // 获取URLConnection对象对应的输出流
  315. out = new PrintWriter(new OutputStreamWriter(httpsUrlConnection.getOutputStream(),"utf-8"));
  316. // 发送请求参数
  317. out.print("&"+param);
  318. // flush输出流的缓冲
  319. out.flush();
  320. if (httpsUrlConnection.getResponseCode()==200) {
  321. // 定义BufferedReader输入流来读取URL的响应
  322. in = new BufferedReader(
  323. new InputStreamReader(httpsUrlConnection.getInputStream(), "utf-8"));
  324. String line;
  325. while ((line = in.readLine()) != null) {
  326. result += line;
  327. }
  328. }else {
  329. result = "获取输入流异常!";
  330. }
  331. } catch (Exception e) {
  332. System.out.println("发送 请求出现异常!" + e);
  333. e.printStackTrace();
  334. }
  335. // 使用finally块来关闭输出流、输入流
  336. finally {
  337. try {
  338. if (out != null) {
  339. out.close();
  340. }
  341. if (in != null) {
  342. in.close();
  343. }
  344. } catch (IOException ex) {
  345. ex.printStackTrace();
  346. }
  347. }
  348. return result;
  349. }
  350. public static String dateToStamp(String s) throws Exception {
  351. String res = "";
  352. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  353. Date date = simpleDateFormat.parse(s);
  354. long time = date.getTime();
  355. res = String.valueOf(time);
  356. return res;
  357. }
  358. /*
  359. * 将时间戳转换为时间
  360. */
  361. public static String stampToDate(String s){
  362. String res;
  363. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  364. long lt = new Long(s);
  365. Date date = new Date(lt);
  366. res = simpleDateFormat.format(date);
  367. return res;
  368. }
  369. public static String sendJson(String request_url, JSONObject json) {
  370. OutputStreamWriter out = null;
  371. InputStream is = null;
  372. String result = "";
  373. try {
  374. URL url = new URL(request_url);// 创建连接
  375. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  376. connection.setDoOutput(true);
  377. connection.setDoInput(true);
  378. connection.setUseCaches(false);
  379. connection.setInstanceFollowRedirects(true);
  380. connection.setRequestMethod("POST"); // 设置请求方式
  381. // 设置接收数据的格式
  382. connection.setRequestProperty("Accept", "application/json");
  383. // 设置发送数据的格式
  384. connection.setRequestProperty("Content-Type", "application/json");
  385. connection.connect();
  386. out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
  387. out.append(json.toString());
  388. out.flush();
  389. out.close();
  390. // 读取响应
  391. is = connection.getInputStream();
  392. int length = (int) connection.getContentLength();// 获取字节长度
  393. System.out.println(length);
  394. if (length != -1) {
  395. byte[] data = new byte[length];
  396. byte[] temp = new byte[512];
  397. int readLen = 0;
  398. int destPos = 0;
  399. while ((readLen = is.read(temp)) > 0) {
  400. System.arraycopy(temp, 0, data, destPos, readLen);
  401. destPos += readLen;
  402. }
  403. result = new String(data, "UTF-8"); // utf-8编码
  404. }
  405. } catch (IOException e) {
  406. e.printStackTrace();
  407. } finally {
  408. try {
  409. is.close();
  410. out.close();
  411. } catch (IOException e) {
  412. e.printStackTrace();
  413. }
  414. }
  415. return result;
  416. }
  417. public static String sendJson2(String request_url, JSONObject json) {
  418. OutputStreamWriter out = null;
  419. InputStream is = null;
  420. String result = "";
  421. try {
  422. URL url = new URL(request_url);// 创建连接
  423. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  424. connection.setDoOutput(true);
  425. connection.setDoInput(true);
  426. connection.setUseCaches(false);
  427. connection.setInstanceFollowRedirects(true);
  428. connection.setRequestMethod("POST"); // 设置请求方式
  429. // 设置接收数据的格式
  430. connection.setRequestProperty("Accept", "application/json");
  431. // 设置发送数据的格式
  432. connection.setRequestProperty("Content-Type", "application/json");
  433. connection.connect();
  434. out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
  435. out.append(json.toString());
  436. out.flush();
  437. out.close();
  438. // 读取响应
  439. is = connection.getInputStream();
  440. BufferedReader in = new BufferedReader(new InputStreamReader(is));
  441. result = in.readLine();
  442. } catch (IOException e) {
  443. e.printStackTrace();
  444. } finally {
  445. try {
  446. is.close();
  447. out.close();
  448. } catch (IOException e) {
  449. e.printStackTrace();
  450. }
  451. }
  452. return result;
  453. }
  454. public static void main(String[] args) throws Exception {
  455. JSONObject json = new JSONObject();
  456. json.put("buildCode", "5栋");
  457. json.put("currentAggr", "20");
  458. json.put("energyType", "2");
  459. json.put("updateTime", "2021-09-09 10:15:33");
  460. String msg = sendJson2("https://chtech.ncjti.edu.cn/bigdata-api/api/energy/energyDataUpload", json);
  461. System.out.println(msg);
  462. }
  463. }