HttpsClient.java 20 KB

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