HttpsClient.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. package com.repair.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.impl.client.CloseableHttpClient;
  13. import org.apache.http.impl.client.HttpClients;
  14. import org.apache.http.message.BasicNameValuePair;
  15. import org.apache.http.util.EntityUtils;
  16. import javax.net.ssl.HttpsURLConnection;
  17. import javax.net.ssl.SSLContext;
  18. import javax.net.ssl.SSLSocketFactory;
  19. import javax.net.ssl.TrustManager;
  20. import java.io.*;
  21. import java.net.HttpURLConnection;
  22. import java.net.URL;
  23. import java.net.URLConnection;
  24. import java.text.SimpleDateFormat;
  25. import java.util.ArrayList;
  26. import java.util.Date;
  27. import java.util.List;
  28. import java.util.Map;
  29. /**
  30. * HttpsClient类
  31. * @author lujunjie
  32. * @date 2018/03/01
  33. */
  34. public class HttpsClient {
  35. /**
  36. * GET请求方式
  37. */
  38. public static final String METHOD_GET = "GET";
  39. /**
  40. * POST请求方式
  41. */
  42. public static final String METHOD_POST = "POST";
  43. /**
  44. * 连接超时时间
  45. */
  46. private static Integer CONNECTION_TIMEOUT = 15000;
  47. /**
  48. * 请求超时时间
  49. */
  50. private static Integer READ_TIMEOUT = 15000;
  51. /**
  52. * 发起https请求
  53. * @param requestUrl 请求地址
  54. * @param requestMethod 请求方式(Get或者post)
  55. * @param postData 提交数据
  56. * @return JSONObject
  57. */
  58. public static JSONObject httpsRequestReturnJSONObject(String requestUrl, String requestMethod, String postData) throws Exception{
  59. JSONObject jsonObject = JSONObject.parseObject(HttpsClient.httpsRequestReturnString(requestUrl,requestMethod,postData));
  60. System.out.println("jsonObjectDate: " + jsonObject);
  61. return jsonObject;
  62. }
  63. /**
  64. * 发起https请求
  65. * @param requestUrl 请求地址
  66. * @param requestMethod 请求方式(Get或者post)
  67. * @param postData 提交数据
  68. * @return String
  69. */
  70. public static String httpsRequestReturnString(String requestUrl, String requestMethod, String postData) throws Exception{
  71. String response;
  72. HttpsURLConnection httpsUrlConnection = null;
  73. try{
  74. //创建https请求证书
  75. TrustManager[] tm={new MyX509TrustManager()};
  76. //创建SSLContext管理器对像,使用我们指定的信任管理器初始化
  77. SSLContext sslContext=SSLContext.getInstance("SSL","SunJSSE");
  78. sslContext.init(null, tm, new java.security.SecureRandom());
  79. SSLSocketFactory ssf=sslContext.getSocketFactory();
  80. // 创建URL对象
  81. URL url= new URL(requestUrl);
  82. // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
  83. httpsUrlConnection=(HttpsURLConnection)url.openConnection();
  84. //设置ssl证书
  85. httpsUrlConnection.setSSLSocketFactory(ssf);
  86. //设置header信息
  87. httpsUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  88. //设置User-Agent信息
  89. 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");
  90. //设置可接受信息
  91. httpsUrlConnection.setDoOutput(true);
  92. //设置可输入信息
  93. httpsUrlConnection.setDoInput(true);
  94. //不使用缓存
  95. httpsUrlConnection.setUseCaches(false);
  96. //设置请求方式(GET/POST)
  97. httpsUrlConnection.setRequestMethod(requestMethod);
  98. //设置连接超时时间
  99. if (CONNECTION_TIMEOUT > 0) {
  100. httpsUrlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
  101. } else {
  102. //默认10秒超时
  103. httpsUrlConnection.setConnectTimeout(10000);
  104. }
  105. //设置请求超时
  106. if (READ_TIMEOUT > 0) {
  107. httpsUrlConnection.setReadTimeout(READ_TIMEOUT);
  108. } else {
  109. //默认10秒超时
  110. httpsUrlConnection.setReadTimeout(10000);
  111. }
  112. //设置编码
  113. httpsUrlConnection.setRequestProperty("Charsert", WxConstants.DEFAULT_CHARSET);
  114. //判断是否需要提交数据
  115. if(StringUtils.equals(requestMethod,HttpsClient.METHOD_POST) && StringUtils.isNotBlank(postData)){
  116. //讲参数转换为字节提交
  117. byte[] bytes = postData.getBytes(WxConstants.DEFAULT_CHARSET);
  118. //设置头信息
  119. httpsUrlConnection.setRequestProperty("Content-Length", Integer.toString(bytes.length));
  120. //开始连接
  121. httpsUrlConnection.connect();
  122. //防止中文乱码
  123. OutputStream outputStream=httpsUrlConnection.getOutputStream();
  124. outputStream.write(postData.getBytes(WxConstants.DEFAULT_CHARSET));
  125. outputStream.flush();
  126. outputStream.close();
  127. }else{
  128. //开始连接
  129. httpsUrlConnection.connect();
  130. }
  131. response = WxUtil.getStreamString(httpsUrlConnection.getInputStream());
  132. }catch (Exception e){
  133. throw new Exception();
  134. }finally {
  135. if (httpsUrlConnection != null) {
  136. // 关闭连接
  137. httpsUrlConnection.disconnect();
  138. }
  139. }
  140. return response;
  141. }
  142. public static String get(String url, Map<String, String> params){
  143. CloseableHttpClient httpClient = null;
  144. HttpGet httpGet = null;
  145. StringBuffer str = new StringBuffer("");
  146. try {
  147. httpClient = HttpClients.createDefault();
  148. RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
  149. String ps = "";
  150. for (String pKey : params.keySet()) {
  151. if(!"".equals(ps)){
  152. ps = ps + "&";
  153. }
  154. ps = pKey+"="+params.get(pKey);
  155. }
  156. if(!"".equals(ps)){
  157. url = url + "?" + ps;
  158. }
  159. httpGet = new HttpGet(url);
  160. httpGet.setConfig(requestConfig);
  161. CloseableHttpResponse response = httpClient.execute(httpGet);
  162. HttpEntity httpEntity = response.getEntity();
  163. str.append(EntityUtils.toString(httpEntity,"utf-8"));
  164. } catch (ClientProtocolException e) {
  165. e.printStackTrace();
  166. } catch (IOException e) {
  167. e.printStackTrace();
  168. }finally{
  169. try {
  170. if(httpGet!=null){
  171. httpGet.releaseConnection();
  172. }
  173. if(httpClient!=null){
  174. httpClient.close();
  175. }
  176. } catch (IOException e) {
  177. e.printStackTrace();
  178. }
  179. }
  180. return str.toString();
  181. }
  182. public static String get(String strURL) throws Exception{
  183. URL url = new URL(strURL);
  184. HttpURLConnection httpConn = (HttpURLConnection)
  185. url.openConnection();
  186. httpConn.setRequestMethod("GET");
  187. httpConn.connect();
  188. System.out.println("bbb: "+httpConn.getResponseCode());
  189. BufferedReader reader = new BufferedReader(new InputStreamReader(
  190. httpConn.getInputStream(),"utf-8"));
  191. String line;
  192. StringBuffer buffer = new StringBuffer();
  193. while ((line = reader.readLine()) != null) {
  194. buffer.append(line);
  195. }
  196. reader.close();
  197. httpConn.disconnect();
  198. return buffer.toString();
  199. }
  200. /**
  201. * 发送 post请求
  202. * @param
  203. * @param
  204. */
  205. public static String post(String url, Map<String, String> params){
  206. CloseableHttpClient httpClient = null;
  207. HttpPost httpPost = null;
  208. StringBuilder sb = new StringBuilder("");
  209. try {
  210. httpClient = HttpClients.createDefault();
  211. RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
  212. httpPost = new HttpPost(url);
  213. httpPost.setConfig(requestConfig);
  214. List<NameValuePair> ps = new ArrayList<NameValuePair>();
  215. for (String pKey : params.keySet()) {
  216. ps.add(new BasicNameValuePair(pKey, params.get(pKey)));
  217. }
  218. httpPost.setEntity(new UrlEncodedFormEntity(ps));
  219. CloseableHttpResponse response = httpClient.execute(httpPost);
  220. HttpEntity httpEntity = response.getEntity();
  221. sb.append(EntityUtils.toString(httpEntity,"utf-8"));
  222. } catch (ClientProtocolException e) {
  223. e.printStackTrace();
  224. } catch (IOException e) {
  225. e.printStackTrace();
  226. }finally{
  227. try {
  228. if(httpPost!=null){
  229. httpPost.releaseConnection();
  230. }
  231. if(httpClient!=null){
  232. httpClient.close();
  233. }
  234. } catch (IOException e) {
  235. e.printStackTrace();
  236. }
  237. }
  238. return sb.toString();
  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. System.out.println("aaa: "+result);
  443. } catch (IOException e) {
  444. e.printStackTrace();
  445. } finally {
  446. try {
  447. is.close();
  448. out.close();
  449. } catch (IOException e) {
  450. e.printStackTrace();
  451. }
  452. }
  453. return result;
  454. }
  455. }