当前位置:   article > 正文

Java发送HTTP/HTTPS请求工具类

Java发送HTTP/HTTPS请求工具类

基于原生JDK的发送HTTP/HTTPS请求工具类。

  1. import java.io.BufferedReader;
  2. import java.io.BufferedWriter;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.io.OutputStreamWriter;
  7. import java.io.UnsupportedEncodingException;
  8. import java.net.HttpURLConnection;
  9. import java.net.URL;
  10. import java.net.URLEncoder;
  11. import java.nio.charset.Charset;
  12. import java.security.KeyManagementException;
  13. import java.security.MessageDigest;
  14. import java.security.NoSuchAlgorithmException;
  15. import java.security.cert.CertificateException;
  16. import java.security.cert.X509Certificate;
  17. import java.util.Base64;
  18. import java.util.HashMap;
  19. import java.util.Map;
  20. import javax.net.ssl.HostnameVerifier;
  21. import javax.net.ssl.HttpsURLConnection;
  22. import javax.net.ssl.SSLContext;
  23. import javax.net.ssl.SSLSession;
  24. import javax.net.ssl.TrustManager;
  25. import javax.net.ssl.X509TrustManager;
  26. /**
  27. * HTTP请求工具
  28. *
  29. */
  30. public class HttpUtil {
  31. /**
  32. * 发送简单GET请求
  33. *
  34. * @param url 请求地址
  35. * @return 请求结果,出现异常返回null
  36. */
  37. public static Result get(String url) {
  38. try {
  39. return sendRequest(url, "GET", null, 0, 0, null, null, null, Charset.forName("UTF-8"),
  40. Charset.forName("UTF-8"), false);
  41. } catch (KeyManagementException | NoSuchAlgorithmException | IOException e) {
  42. // TODO
  43. e.printStackTrace();
  44. }
  45. return null;
  46. }
  47. /**
  48. * 发送简单POST请求
  49. *
  50. * @param url 请求地址
  51. * @param body 请求体
  52. * @return 请求结果,出现异常返回null
  53. */
  54. public static Result post(String url, String body) {
  55. try {
  56. return sendRequest(url, "POST", null, 0, 0, null, null, body, Charset.forName("UTF-8"),
  57. Charset.forName("UTF-8"), false);
  58. } catch (KeyManagementException | NoSuchAlgorithmException | IOException e) {
  59. // TODO
  60. e.printStackTrace();
  61. }
  62. return null;
  63. }
  64. /**
  65. * 发送简单POST请求
  66. *
  67. * @param url 请求地址
  68. * @param body 请求体
  69. * @param contentType 请求体类型
  70. * @return 请求结果,出现异常返回null
  71. */
  72. public static Result post(String url, String body, String contentType) {
  73. Map<String, String> header = new HashMap<>();
  74. header.put("Content-Type", contentType);
  75. try {
  76. return sendRequest(url, "POST", null, 0, 0, header, null, body, Charset.forName("UTF-8"),
  77. Charset.forName("UTF-8"), false);
  78. } catch (KeyManagementException | NoSuchAlgorithmException | IOException e) {
  79. // TODO
  80. e.printStackTrace();
  81. }
  82. return null;
  83. }
  84. /**
  85. * 发送简单POST请求
  86. *
  87. * @param url 请求地址
  88. * @param body 请求体
  89. * @param header 请求头
  90. * @return 请求结果,出现异常返回null
  91. */
  92. public static Result post(String url, String body, Map<String, String> header) {
  93. try {
  94. return sendRequest(url, "POST", null, 0, 0, header, null, body, Charset.forName("UTF-8"),
  95. Charset.forName("UTF-8"), false);
  96. } catch (KeyManagementException | NoSuchAlgorithmException | IOException e) {
  97. // TODO
  98. e.printStackTrace();
  99. }
  100. return null;
  101. }
  102. /**
  103. * 发送请求
  104. *
  105. * @param url 请求地址
  106. * @param methodType 请求类型,POST/GET
  107. * @param protocol HTTPS使用的加密协议,传入null则使用SSL协议
  108. * @param connectTimeout 连接超时时间
  109. * @param readTimeout 读回应超时时间
  110. * @param header 请求头
  111. * @param cookie cookie
  112. * @param body 请求体
  113. * @param outCharset 发送请求采用的字符编码
  114. * @param inCharset 读回应采用的字符编码
  115. * @param useCahces 是否启用缓存,建议false
  116. * @return 请求结果
  117. * @throws IOException 网络流异常
  118. * @throws KeyManagementException 证书异常
  119. * @throws NoSuchAlgorithmException 加密协议无效
  120. */
  121. public static Result sendRequest(String url, String methodType, String protocol, int connectTimeout,
  122. int readTimeout, Map<String, String> header, Map<String, String> cookie, String body, Charset outCharset,
  123. Charset inCharset, boolean useCahces) throws IOException, KeyManagementException, NoSuchAlgorithmException {
  124. if (isBlankStr(url)) {
  125. throw new RuntimeException("未传入有效URL!URL=" + url);
  126. }
  127. if (url.trim().toLowerCase().startsWith("http://")) {
  128. return Http.sendRequest(url, methodType, connectTimeout, readTimeout, header, cookie, body, outCharset,
  129. inCharset, useCahces);
  130. } else if (url.trim().toLowerCase().startsWith("https://")) {
  131. return Https.sendRequest(url, methodType, protocol, connectTimeout, readTimeout, header, cookie, body,
  132. outCharset, inCharset, useCahces);
  133. } else {
  134. throw new RuntimeException("不是HTTP或HTTPS地址!URL=" + url);
  135. }
  136. }
  137. /**
  138. * 判断字符串是否无内容
  139. *
  140. * @param str
  141. * @return 无内容返回true,否则返回false
  142. */
  143. private static boolean isBlankStr(String str) {
  144. int strLen;
  145. if (str == null || (strLen = str.length()) == 0) {
  146. return true;
  147. }
  148. for (int i = 0; i < strLen; i++) {
  149. if (!Character.isWhitespace(str.charAt(i))) {
  150. return false;
  151. }
  152. }
  153. return true;
  154. }
  155. /**
  156. * base64加密
  157. */
  158. public static String base64Encode(String original) {
  159. try {
  160. return new String(Base64.getEncoder().encode(original.getBytes("UTF-8")));
  161. } catch (UnsupportedEncodingException e) {
  162. e.printStackTrace();
  163. }
  164. return null;
  165. }
  166. /**
  167. * base64解密字
  168. */
  169. public static String base64Decode(String ciphertext) {
  170. try {
  171. return new String(Base64.getDecoder().decode(ciphertext.getBytes("UTF-8")));
  172. } catch (UnsupportedEncodingException e) {
  173. e.printStackTrace();
  174. }
  175. return null;
  176. }
  177. /***
  178. * MD5加密
  179. *
  180. * @param original 原文
  181. * @return 密文,字母小写
  182. */
  183. public static String md5(String original) {
  184. try {
  185. MessageDigest md5 = MessageDigest.getInstance("MD5");// 此 MessageDigest 类为应用程序提供信息摘要算法的功能
  186. byte[] digest = md5.digest(original.getBytes("UTF-8")); // 转换为MD5码
  187. StringBuilder resultHexString = new StringBuilder();
  188. String tempStr;
  189. for (byte b : digest) {
  190. tempStr = Integer.toHexString(b & 0xff); // 这里需要对b与0xff做位与运算,若b为负数,强制转换将高位位扩展会导致错误,故需要高位清零
  191. if (tempStr.length() == 1) { // 若转换后的十六进制数字只有一位,则在前补"0"
  192. resultHexString.append(0).append(tempStr);
  193. } else {
  194. resultHexString.append(tempStr);
  195. }
  196. }
  197. return resultHexString.toString();
  198. } catch (NoSuchAlgorithmException e) {
  199. e.printStackTrace();
  200. } catch (UnsupportedEncodingException e) {
  201. e.printStackTrace();
  202. }
  203. return null;
  204. }
  205. /**
  206. * 请求返回值模型
  207. */
  208. public static class Result {
  209. private int code;// 请求返回的状态码
  210. private String content;// 请求返回的内容文本
  211. public int getCode() {
  212. return code;
  213. }
  214. public void setCode(int code) {
  215. this.code = code;
  216. }
  217. public String getContent() {
  218. return content;
  219. }
  220. public void setContent(String content) {
  221. this.content = content;
  222. }
  223. @Override
  224. public String toString() {
  225. return "Result [code=" + code + ", content=" + content + "]";
  226. }
  227. }
  228. /**
  229. * HTTP请求实现
  230. */
  231. public static class Http {
  232. /**
  233. * @param url 请求地址
  234. * @param methodType 请求类型,POST/GET
  235. * @param connectTimeout 连接超时时间
  236. * @param readTimeout 读回应超时时间
  237. * @param header 请求头
  238. * @param cookie cookie
  239. * @param body 请求体
  240. * @param outCharset 发送请求采用的字符编码
  241. * @param inCharset 读回应采用的字符编码
  242. * @param useCahces 是否启用缓存,建议false
  243. * @return 返回结果
  244. * @throws IOException 网络流异常
  245. */
  246. public static Result sendRequest(String url, String methodType, int connectTimeout, int readTimeout,
  247. Map<String, String> header, Map<String, String> cookie, String body, Charset outCharset,
  248. Charset inCharset, boolean useCahces) throws IOException {
  249. HttpURLConnection con = null;
  250. // // 添加请求参数
  251. // if (params != null) {
  252. // for (String headerKey : header.keySet()) {
  253. // con.setRequestProperty(headerKey, header.get(headerKey));// 设置请求属性
  254. // }
  255. // }
  256. URL urlObject = new URL(url);
  257. con = (HttpURLConnection) urlObject.openConnection(); // 得到连接对象
  258. con.setRequestMethod(methodType); // 设置请求类型
  259. // 连接超时时间
  260. if (connectTimeout >= 0) {
  261. con.setConnectTimeout(connectTimeout);
  262. }
  263. // 读取超时时间
  264. if (readTimeout >= 0) {
  265. con.setReadTimeout(readTimeout);
  266. }
  267. // 添加请求头
  268. if (header != null) {
  269. for (String headerKey : header.keySet()) {
  270. con.setRequestProperty(headerKey, header.get(headerKey));// 设置请求属性
  271. }
  272. }
  273. // 添加cookie
  274. if (cookie != null) {
  275. StringBuilder c = new StringBuilder();
  276. for (String name : cookie.keySet()) {
  277. String value = cookie.get(name);
  278. if (value == null) {
  279. continue;
  280. }
  281. value = URLEncoder.encode(value, outCharset.name());
  282. c.append(name + "=" + value + ";");
  283. }
  284. c.deleteCharAt(c.length() - 2);
  285. con.setRequestProperty("Cookie", c.toString());// 设置请求属性
  286. }
  287. con.setDoOutput(true); // 允许写出
  288. con.setDoInput(true); // 允许读入
  289. con.setUseCaches(useCahces);// 是否使用缓存
  290. // 写入请求体
  291. if (body != null) {
  292. BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(con.getOutputStream(), outCharset));
  293. bw.write(body);
  294. bw.close();
  295. }
  296. int responseCode = con.getResponseCode(); // 得到响应码
  297. Result result = new Result();
  298. InputStream is = null;
  299. if (responseCode == HttpURLConnection.HTTP_OK) { // 正常返回状态码
  300. is = con.getInputStream();
  301. } else { // 400、401等其他错误类型
  302. is = con.getErrorStream();
  303. }
  304. BufferedReader in = null;
  305. in = new BufferedReader(new InputStreamReader(is, inCharset));
  306. StringBuilder resultBuffer = new StringBuilder();// 将响应流转换成字符串
  307. String line = "";
  308. while ((line = in.readLine()) != null) {
  309. resultBuffer.append(line);
  310. }
  311. result.setCode(responseCode);
  312. result.setContent(resultBuffer.toString());
  313. if (null != is) {
  314. is.close();
  315. }
  316. if (null != in) {
  317. in.close();
  318. }
  319. con.disconnect();// 关闭连接
  320. return result;
  321. }
  322. }
  323. /**
  324. * HTTPS类型请求实现
  325. */
  326. public static class Https {
  327. /**
  328. * 发送请求
  329. *
  330. * @param url 请求地址
  331. * @param methodType 请求类型,POST/GET
  332. * @param protocol HTTPS使用的加密协议,传入null则使用SSL协议
  333. * @param connectTimeout 连接超时时间
  334. * @param readTimeout 读回应超时时间
  335. * @param header 请求头
  336. * @param cookie cookie
  337. * @param body 请求体
  338. * @param outCharset 是否启用缓存,建议false
  339. * @param inCharset 发送请求采用的字符编码
  340. * @param useCahces 读回应采用的字符编码
  341. * @return 返回结果
  342. * @throws IOException
  343. * @throws KeyManagementException 秘钥异常
  344. * @throws NoSuchAlgorithmException 找不到加密协议
  345. */
  346. public static Result sendRequest(String url, String methodType, String protocol, int connectTimeout,
  347. int readTimeout, Map<String, String> header, Map<String, String> cookie, String body,
  348. Charset outCharset, Charset inCharset, boolean useCahces)
  349. throws IOException, KeyManagementException, NoSuchAlgorithmException {
  350. HttpsURLConnection connection = null;
  351. if (protocol == null) {
  352. protocol = "SSL";// 默认协议
  353. }
  354. trustAllHttpsCertificates(protocol);// 信任所有证书
  355. URL realUrl = new URL(url);
  356. connection = (HttpsURLConnection) realUrl.openConnection();// 转为HTTPS
  357. connection.setHostnameVerifier(getHostnameVerifier());// 主机验证规则
  358. connection.setDoOutput(true);// 输出(发送数据)
  359. connection.setDoInput(true);// 输入(接收数据)
  360. connection.setUseCaches(useCahces); // 设置是否开启缓存,post请求时,缓存必须关掉
  361. connection.setRequestMethod(methodType); // 请求方法
  362. // 超时时间
  363. if (connectTimeout >= 0) {
  364. connection.setConnectTimeout(connectTimeout);
  365. }
  366. // 读取超时时间
  367. if (readTimeout >= 0) {
  368. connection.setReadTimeout(readTimeout);
  369. }
  370. // 添加请求头
  371. if (header != null) {
  372. for (String headerKey : header.keySet()) {
  373. connection.setRequestProperty(headerKey, header.get(headerKey));// 设置请求属性
  374. }
  375. }
  376. // 添加cookie
  377. if (cookie != null) {
  378. StringBuilder c = new StringBuilder();
  379. for (String name : cookie.keySet()) {
  380. String value = cookie.get(name);
  381. if (value == null) {
  382. continue;
  383. }
  384. value = URLEncoder.encode(value, outCharset.name());
  385. c.append(name + "=" + value + ";");
  386. }
  387. c.deleteCharAt(c.length() - 2);
  388. connection.setRequestProperty("Cookie", c.toString());// 设置请求属性
  389. }
  390. // 写入请求体
  391. if (body != null) {
  392. BufferedWriter bw = new BufferedWriter(
  393. new OutputStreamWriter(connection.getOutputStream(), outCharset));
  394. bw.write(body);
  395. bw.flush();
  396. bw.close();
  397. }
  398. InputStream is = null;
  399. BufferedReader in = null;
  400. StringBuffer resultStr = new StringBuffer();
  401. int responseCode = connection.getResponseCode();// 请求响应码
  402. if (responseCode == HttpURLConnection.HTTP_OK) { // 正常返回状态码200
  403. is = connection.getInputStream();
  404. } else { // 400、401等其他错误类型
  405. is = connection.getErrorStream();
  406. }
  407. in = new BufferedReader(new InputStreamReader(is, inCharset));
  408. String line = "";
  409. while ((line = in.readLine()) != null) {
  410. resultStr.append(line);
  411. }
  412. Result result = new Result();
  413. result.setCode(responseCode);
  414. result.setContent(resultStr.toString());
  415. if (null != is) {
  416. is.close();
  417. }
  418. if (null != in) {
  419. in.close();
  420. }
  421. connection.disconnect();
  422. return result;
  423. }
  424. /**
  425. * 信任所有证书
  426. */
  427. private static void trustAllHttpsCertificates(String protocol)
  428. throws KeyManagementException, NoSuchAlgorithmException {
  429. TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
  430. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  431. return;
  432. }
  433. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  434. return;
  435. }
  436. public X509Certificate[] getAcceptedIssuers() {
  437. return null;
  438. }
  439. } };
  440. SSLContext sc = SSLContext.getInstance(protocol);
  441. sc.init(null, trustAllCerts, null);
  442. HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  443. }
  444. /**
  445. * 所有主机验证都通过
  446. *
  447. * @return 主机验证对象
  448. */
  449. private static HostnameVerifier getHostnameVerifier() {
  450. return new HostnameVerifier() {
  451. @Override
  452. public boolean verify(String hostname, SSLSession session) {
  453. return true;
  454. }
  455. };
  456. }
  457. }
  458. }

使用方式如下:

  1. import java.io.IOException;
  2. import java.nio.charset.Charset;
  3. import java.security.KeyManagementException;
  4. import java.security.NoSuchAlgorithmException;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. import util.HttpUtil;
  8. public class Test {
  9. public static void main(String[] args) {
  10. HttpUtil.Result getResult = HttpUtil.get("http://127.0.0.1:8080");
  11. System.out.println(getResult.getContent());
  12. HttpUtil.Result psotResult1 = HttpUtil.post("http://127.0.0.1:8080/api/sms/send", "name=shencomd");
  13. System.out.println(psotResult1.getContent());
  14. HttpUtil.Result psotResult2 = HttpUtil.post("http://127.0.0.1:8080/api/sms/send", "{\"name\":\"shencomd\"}",
  15. "application/json");
  16. System.out.println(psotResult2.getContent());
  17. String url = "https://127.0.0.1:8082/api/sms/send";// 请求地址
  18. String method = "POST";// 请求类型
  19. int connectTimeout = 0;// 连接超时时间
  20. int readTimeout = 0; // 读回应超时时间
  21. String protocol = "SSL";// 加密协议
  22. Map<String, String> header = new HashMap<>();// 请求头
  23. header.put("Content-Type", "application/json");
  24. Map<String, String> cookie = new HashMap<>();
  25. cookie.put("sessionid", "asiuqwenqweasga");
  26. String body = "{\"name\":\"shencomd\"}";// 请求体
  27. Charset outCharset = Charset.forName("utf-8"); // 发送请求采用的字符编码
  28. Charset inCharset = Charset.forName("utf-8"); // 读回应采用的字符编码
  29. boolean useCahces = false; // 是否启用缓存
  30. try {
  31. HttpUtil.Result psotResult3 = HttpUtil.sendRequest(url, method, protocol, connectTimeout, readTimeout,
  32. header, cookie, body, outCharset, inCharset, useCahces);
  33. if (psotResult3.getCode() == 200) {
  34. System.out.println(psotResult3.getContent());
  35. } else {
  36. System.out.println("请求发生错误,结果如下:");
  37. System.out.println(psotResult3.getContent());
  38. }
  39. } catch (KeyManagementException | NoSuchAlgorithmException | IOException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. }

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号