基于原生JDK的发送HTTP/HTTPS请求工具类。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;/*** HTTP请求工具**/
public class HttpUtil {/*** 发送简单GET请求* * @param url 请求地址* @return 请求结果,出现异常返回null*/public static Result get(String url) {try {return sendRequest(url, "GET", null, 0, 0, null, null, null, Charset.forName("UTF-8"),Charset.forName("UTF-8"), false);} catch (KeyManagementException | NoSuchAlgorithmException | IOException e) {// TODOe.printStackTrace();}return null;}/*** 发送简单POST请求* * @param url 请求地址* @param body 请求体* @return 请求结果,出现异常返回null*/public static Result post(String url, String body) {try {return sendRequest(url, "POST", null, 0, 0, null, null, body, Charset.forName("UTF-8"),Charset.forName("UTF-8"), false);} catch (KeyManagementException | NoSuchAlgorithmException | IOException e) {// TODOe.printStackTrace();}return null;}/*** 发送简单POST请求* * @param url 请求地址* @param body 请求体* @param contentType 请求体类型* @return 请求结果,出现异常返回null*/public static Result post(String url, String body, String contentType) {Map<String, String> header = new HashMap<>();header.put("Content-Type", contentType);try {return sendRequest(url, "POST", null, 0, 0, header, null, body, Charset.forName("UTF-8"),Charset.forName("UTF-8"), false);} catch (KeyManagementException | NoSuchAlgorithmException | IOException e) {// TODOe.printStackTrace();}return null;}/*** 发送简单POST请求* * @param url 请求地址* @param body 请求体* @param header 请求头* @return 请求结果,出现异常返回null*/public static Result post(String url, String body, Map<String, String> header) {try {return sendRequest(url, "POST", null, 0, 0, header, null, body, Charset.forName("UTF-8"),Charset.forName("UTF-8"), false);} catch (KeyManagementException | NoSuchAlgorithmException | IOException e) {// TODOe.printStackTrace();}return null;}/*** 发送请求* * @param url 请求地址* @param methodType 请求类型,POST/GET* @param protocol HTTPS使用的加密协议,传入null则使用SSL协议* @param connectTimeout 连接超时时间* @param readTimeout 读回应超时时间* @param header 请求头* @param cookie cookie* @param body 请求体* @param outCharset 发送请求采用的字符编码* @param inCharset 读回应采用的字符编码* @param useCahces 是否启用缓存,建议false* @return 请求结果* @throws IOException 网络流异常* @throws KeyManagementException 证书异常* @throws NoSuchAlgorithmException 加密协议无效*/public static Result sendRequest(String url, String methodType, String protocol, int connectTimeout,int readTimeout, Map<String, String> header, Map<String, String> cookie, String body, Charset outCharset,Charset inCharset, boolean useCahces) throws IOException, KeyManagementException, NoSuchAlgorithmException {if (isBlankStr(url)) {throw new RuntimeException("未传入有效URL!URL=" + url);}if (url.trim().toLowerCase().startsWith("http://")) {return Http.sendRequest(url, methodType, connectTimeout, readTimeout, header, cookie, body, outCharset,inCharset, useCahces);} else if (url.trim().toLowerCase().startsWith("https://")) {return Https.sendRequest(url, methodType, protocol, connectTimeout, readTimeout, header, cookie, body,outCharset, inCharset, useCahces);} else {throw new RuntimeException("不是HTTP或HTTPS地址!URL=" + url);}}/*** 判断字符串是否无内容* * @param str* @return 无内容返回true,否则返回false*/private static boolean isBlankStr(String str) {int strLen;if (str == null || (strLen = str.length()) == 0) {return true;}for (int i = 0; i < strLen; i++) {if (!Character.isWhitespace(str.charAt(i))) {return false;}}return true;}/*** base64加密*/public static String base64Encode(String original) {try {return new String(Base64.getEncoder().encode(original.getBytes("UTF-8")));} catch (UnsupportedEncodingException e) {e.printStackTrace();}return null;}/*** base64解密字*/public static String base64Decode(String ciphertext) {try {return new String(Base64.getDecoder().decode(ciphertext.getBytes("UTF-8")));} catch (UnsupportedEncodingException e) {e.printStackTrace();}return null;}/**** MD5加密* * @param original 原文* @return 密文,字母小写*/public static String md5(String original) {try {MessageDigest md5 = MessageDigest.getInstance("MD5");// 此 MessageDigest 类为应用程序提供信息摘要算法的功能byte[] digest = md5.digest(original.getBytes("UTF-8")); // 转换为MD5码StringBuilder resultHexString = new StringBuilder();String tempStr;for (byte b : digest) {tempStr = Integer.toHexString(b & 0xff); // 这里需要对b与0xff做位与运算,若b为负数,强制转换将高位位扩展会导致错误,故需要高位清零if (tempStr.length() == 1) { // 若转换后的十六进制数字只有一位,则在前补"0"resultHexString.append(0).append(tempStr);} else {resultHexString.append(tempStr);}}return resultHexString.toString();} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();}return null;}/*** 请求返回值模型*/public static class Result {private int code;// 请求返回的状态码private String content;// 请求返回的内容文本public int getCode() {return code;}public void setCode(int code) {this.code = code;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}@Overridepublic String toString() {return "Result [code=" + code + ", content=" + content + "]";}}/*** HTTP请求实现*/public static class Http {/*** @param url 请求地址* @param methodType 请求类型,POST/GET* @param connectTimeout 连接超时时间* @param readTimeout 读回应超时时间* @param header 请求头* @param cookie cookie* @param body 请求体* @param outCharset 发送请求采用的字符编码* @param inCharset 读回应采用的字符编码* @param useCahces 是否启用缓存,建议false* @return 返回结果* @throws IOException 网络流异常*/public static Result sendRequest(String url, String methodType, int connectTimeout, int readTimeout,Map<String, String> header, Map<String, String> cookie, String body, Charset outCharset,Charset inCharset, boolean useCahces) throws IOException {HttpURLConnection con = null;// // 添加请求参数
// if (params != null) {
// for (String headerKey : header.keySet()) {
// con.setRequestProperty(headerKey, header.get(headerKey));// 设置请求属性
// }
// }URL urlObject = new URL(url);con = (HttpURLConnection) urlObject.openConnection(); // 得到连接对象con.setRequestMethod(methodType); // 设置请求类型// 连接超时时间if (connectTimeout >= 0) {con.setConnectTimeout(connectTimeout);}// 读取超时时间if (readTimeout >= 0) {con.setReadTimeout(readTimeout);}// 添加请求头if (header != null) {for (String headerKey : header.keySet()) {con.setRequestProperty(headerKey, header.get(headerKey));// 设置请求属性}}// 添加cookieif (cookie != null) {StringBuilder c = new StringBuilder();for (String name : cookie.keySet()) {String value = cookie.get(name);if (value == null) {continue;}value = URLEncoder.encode(value, outCharset.name());c.append(name + "=" + value + ";");}c.deleteCharAt(c.length() - 2);con.setRequestProperty("Cookie", c.toString());// 设置请求属性}con.setDoOutput(true); // 允许写出con.setDoInput(true); // 允许读入con.setUseCaches(useCahces);// 是否使用缓存// 写入请求体if (body != null) {BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(con.getOutputStream(), outCharset));bw.write(body);bw.close();}int responseCode = con.getResponseCode(); // 得到响应码Result result = new Result();InputStream is = null;if (responseCode == HttpURLConnection.HTTP_OK) { // 正常返回状态码is = con.getInputStream();} else { // 400、401等其他错误类型is = con.getErrorStream();}BufferedReader in = null;in = new BufferedReader(new InputStreamReader(is, inCharset));StringBuilder resultBuffer = new StringBuilder();// 将响应流转换成字符串String line = "";while ((line = in.readLine()) != null) {resultBuffer.append(line);}result.setCode(responseCode);result.setContent(resultBuffer.toString());if (null != is) {is.close();}if (null != in) {in.close();}con.disconnect();// 关闭连接return result;}}/*** HTTPS类型请求实现*/public static class Https {/*** 发送请求* * @param url 请求地址* @param methodType 请求类型,POST/GET* @param protocol HTTPS使用的加密协议,传入null则使用SSL协议* @param connectTimeout 连接超时时间* @param readTimeout 读回应超时时间* @param header 请求头* @param cookie cookie* @param body 请求体* @param outCharset 是否启用缓存,建议false* @param inCharset 发送请求采用的字符编码* @param useCahces 读回应采用的字符编码* @return 返回结果* @throws IOException* @throws KeyManagementException 秘钥异常* @throws NoSuchAlgorithmException 找不到加密协议*/public static Result sendRequest(String url, String methodType, String protocol, int connectTimeout,int readTimeout, Map<String, String> header, Map<String, String> cookie, String body,Charset outCharset, Charset inCharset, boolean useCahces)throws IOException, KeyManagementException, NoSuchAlgorithmException {HttpsURLConnection connection = null;if (protocol == null) {protocol = "SSL";// 默认协议}trustAllHttpsCertificates(protocol);// 信任所有证书URL realUrl = new URL(url);connection = (HttpsURLConnection) realUrl.openConnection();// 转为HTTPSconnection.setHostnameVerifier(getHostnameVerifier());// 主机验证规则connection.setDoOutput(true);// 输出(发送数据)connection.setDoInput(true);// 输入(接收数据)connection.setUseCaches(useCahces); // 设置是否开启缓存,post请求时,缓存必须关掉connection.setRequestMethod(methodType); // 请求方法// 超时时间if (connectTimeout >= 0) {connection.setConnectTimeout(connectTimeout);}// 读取超时时间if (readTimeout >= 0) {connection.setReadTimeout(readTimeout);}// 添加请求头if (header != null) {for (String headerKey : header.keySet()) {connection.setRequestProperty(headerKey, header.get(headerKey));// 设置请求属性}}// 添加cookieif (cookie != null) {StringBuilder c = new StringBuilder();for (String name : cookie.keySet()) {String value = cookie.get(name);if (value == null) {continue;}value = URLEncoder.encode(value, outCharset.name());c.append(name + "=" + value + ";");}c.deleteCharAt(c.length() - 2);connection.setRequestProperty("Cookie", c.toString());// 设置请求属性}// 写入请求体if (body != null) {BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), outCharset));bw.write(body);bw.flush();bw.close();}InputStream is = null;BufferedReader in = null;StringBuffer resultStr = new StringBuffer();int responseCode = connection.getResponseCode();// 请求响应码if (responseCode == HttpURLConnection.HTTP_OK) { // 正常返回状态码200is = connection.getInputStream();} else { // 400、401等其他错误类型is = connection.getErrorStream();}in = new BufferedReader(new InputStreamReader(is, inCharset));String line = "";while ((line = in.readLine()) != null) {resultStr.append(line);}Result result = new Result();result.setCode(responseCode);result.setContent(resultStr.toString());if (null != is) {is.close();}if (null != in) {in.close();}connection.disconnect();return result;}/*** 信任所有证书*/private static void trustAllHttpsCertificates(String protocol)throws KeyManagementException, NoSuchAlgorithmException {TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {return;}public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {return;}public X509Certificate[] getAcceptedIssuers() {return null;}} };SSLContext sc = SSLContext.getInstance(protocol);sc.init(null, trustAllCerts, null);HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());}/*** 所有主机验证都通过* * @return 主机验证对象*/private static HostnameVerifier getHostnameVerifier() {return new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}};}}
}
使用方式如下:
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;import util.HttpUtil;public class Test {public static void main(String[] args) {HttpUtil.Result getResult = HttpUtil.get("http://127.0.0.1:8080");System.out.println(getResult.getContent());HttpUtil.Result psotResult1 = HttpUtil.post("http://127.0.0.1:8080/api/sms/send", "name=shencomd");System.out.println(psotResult1.getContent());HttpUtil.Result psotResult2 = HttpUtil.post("http://127.0.0.1:8080/api/sms/send", "{\"name\":\"shencomd\"}","application/json");System.out.println(psotResult2.getContent());String url = "https://127.0.0.1:8082/api/sms/send";// 请求地址String method = "POST";// 请求类型int connectTimeout = 0;// 连接超时时间int readTimeout = 0; // 读回应超时时间String protocol = "SSL";// 加密协议Map<String, String> header = new HashMap<>();// 请求头header.put("Content-Type", "application/json");Map<String, String> cookie = new HashMap<>();cookie.put("sessionid", "asiuqwenqweasga");String body = "{\"name\":\"shencomd\"}";// 请求体Charset outCharset = Charset.forName("utf-8"); // 发送请求采用的字符编码Charset inCharset = Charset.forName("utf-8"); // 读回应采用的字符编码boolean useCahces = false; // 是否启用缓存try {HttpUtil.Result psotResult3 = HttpUtil.sendRequest(url, method, protocol, connectTimeout, readTimeout,header, cookie, body, outCharset, inCharset, useCahces);if (psotResult3.getCode() == 200) {System.out.println(psotResult3.getContent());} else {System.out.println("请求发生错误,结果如下:");System.out.println(psotResult3.getContent());}} catch (KeyManagementException | NoSuchAlgorithmException | IOException e) {e.printStackTrace();}}
}