HttpsClient.java 20 KB

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