HttpsClient.java 19 KB

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