HttpsClient.java 20 KB

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