总结:封装Java后端开发中常用的HttpUtil工具类,以及如何利用HttpURLConnection访问需要账号密码的URL
一·写这篇博客的背景:
(1)Java程序后端开发中,经常会需要发起http请求从某个接口获取对应的报文信息
(2)本文只利用JDK8原生API(HttpURLConnection),封装一个发起http请求的工具类
(3)本工具类暂时只有get、post两种类型请求
(4)本工具类封装的请求方法中包括各种http请求细节设置,例如:如何设置请求头、post请求如何将参数写入进去、如何设置访问URL所需的账号密码、如何获取异常响应流等等
(5)HttpURLConnection类仅默认信任CA机构签发的有效证书,其他自签证书都是不信任的,也就有可能导致该工具类不会发起https请求
这句话如何理解?
(1)本文章封装的工具类发送可以发送所有http协议请求;
(2)对于https协议请求,只有当服务器是使用正规CA机构签发的证书时,该工具类才能正确发送请求获取响应结果。
比如利用该工具类访问“https://www.baidu.com”,就可以正常接收响应结果。
(3)如果有的公司服务器是使用自签证书,那该工具类是不会发送任何https请求的
什么是证书?
(1)服务器申请或者生成证书时,证书里面会包含公钥、私钥。
(2)客户端第一次发起请求时(此时未加密),服务器就会将只包含公钥的证书发给客户端,从而进行后续的加密通信请求
(3)详情可以去参考https协议
二·完整工具类封装代码:
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
public class HttpUtil {
private static int timeOut = 60000;
public static String doGet(String requestURL) throws IOException {
BufferedReader inReader = null;
InputStream in = null;
String responseBody = "";
try {
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(timeOut);
conn.setReadTimeout(timeOut);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
conn.connect();
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
in = conn.getInputStream();
} else {
in = conn.getErrorStream();
}
inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
int len;
char[] tmp = new char[256];
while ((len = inReader.read(tmp)) > 0) {
sb.append(tmp, 0, len);
}
responseBody = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inReader != null) {
inReader.close();
}
if (in != null) {
in.close();
}
}
return responseBody;
}
public static String doGet(String requestURL, Map<String, String> requestPropertyMap) throws IOException {
BufferedReader inReader = null;
InputStream in = null;
String responseBody = "";
try {
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(timeOut);
conn.setReadTimeout(timeOut);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
if (!requestPropertyMap.isEmpty()) {
for (String key : requestPropertyMap.keySet()) {
conn.setRequestProperty(key, requestPropertyMap.get(key));
}
}
conn.connect();
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
in = conn.getInputStream();
} else {
in = conn.getErrorStream();
}
inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
int len;
char[] tmp = new char[256];
while ((len = inReader.read(tmp)) > 0) {
sb.append(tmp, 0, len);
}
responseBody = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inReader != null) {
inReader.close();
}
if (in != null) {
in.close();
}
}
return responseBody;
}
public static String doGet(String requestURL, String username, String password) throws IOException {
BufferedReader inReader = null;
InputStream in = null;
String responseBody = "";
try {
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(timeOut);
conn.setReadTimeout(timeOut);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
Base64.Encoder encoder = Base64.getEncoder();
String encode = encoder.encodeToString((username + ":" + password).getBytes());
conn.setRequestProperty("Authorization", "Basic " + encode);
conn.connect();
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
in = conn.getInputStream();
} else {
in = conn.getErrorStream();
}
inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
int len;
char[] tmp = new char[256];
while ((len = inReader.read(tmp)) > 0) {
sb.append(tmp, 0, len);
}
responseBody = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inReader != null) {
inReader.close();
}
if (in != null) {
in.close();
}
}
return responseBody;
}
public static String doGet(String requestURL, Map<String, String> requestPropertyMap, String username, String password) throws IOException {
BufferedReader inReader = null;
InputStream in = null;
String responseBody = "";
try {
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(timeOut);
conn.setReadTimeout(timeOut);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
if (!requestPropertyMap.isEmpty()) {
for (String key : requestPropertyMap.keySet()) {
conn.setRequestProperty(key, requestPropertyMap.get(key));
}
}
Base64.Encoder encoder = Base64.getEncoder();
String encode = encoder.encodeToString((username + ":" + password).getBytes());
conn.setRequestProperty("Authorization", "Basic " + encode);
conn.connect();
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
in = conn.getInputStream();
} else {
in = conn.getErrorStream();
}
inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
int len;
char[] tmp = new char[256];
while ((len = inReader.read(tmp)) > 0) {
sb.append(tmp, 0, len);
}
responseBody = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inReader != null) {
inReader.close();
}
if (in != null) {
in.close();
}
}
return responseBody;
}
public static String doPost(String requestURL, String body) throws IOException {
BufferedReader inReader = null;
InputStream in = null;
String responseBody = "";
OutputStream outputStream = null;
BufferedWriter writer = null;
try {
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(timeOut);
conn.setReadTimeout(timeOut);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.connect();
outputStream = conn.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
writer.write(body);
writer.flush();
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
in = conn.getInputStream();
} else {
in = conn.getErrorStream();
}
inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
int len;
char[] tmp = new char[256];
while ((len = inReader.read(tmp)) > 0) {
sb.append(tmp, 0, len);
}
responseBody = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.close();
}
if (outputStream != null) {
outputStream.close();
}
if (inReader != null) {
inReader.close();
}
if (in != null) {
in.close();
}
}
return responseBody;
}
public static String doPost(String requestURL, String body, String username, String password) throws IOException {
BufferedReader inReader = null;
InputStream in = null;
String responseBody = "";
OutputStream outputStream = null;
BufferedWriter writer = null;
try {
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(timeOut);
conn.setReadTimeout(timeOut);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
Base64.Encoder encoder = Base64.getEncoder();
String encode = encoder.encodeToString((username + ":" + password).getBytes());
conn.setRequestProperty("Authorization", "Basic " + encode);
conn.connect();
outputStream = conn.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
writer.write(body);
writer.flush();
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
in = conn.getInputStream();
} else {
in = conn.getErrorStream();
}
inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
int len;
char[] tmp = new char[256];
while ((len = inReader.read(tmp)) > 0) {
sb.append(tmp, 0, len);
}
responseBody = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.close();
}
if (outputStream != null) {
outputStream.close();
}
if (inReader != null) {
inReader.close();
}
if (in != null) {
in.close();
}
}
return responseBody;
}
}
三·GET请求封装代码:
private static int timeOut = 60000;
public static String doGet(String requestURL) throws IOException {
BufferedReader inReader = null;
InputStream in = null;
String responseBody = "";
try {
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(timeOut);
conn.setReadTimeout(timeOut);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
conn.connect();
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
in = conn.getInputStream();
} else {
in = conn.getErrorStream();
}
inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
int len;
char[] tmp = new char[256];
while ((len = inReader.read(tmp)) > 0) {
sb.append(tmp, 0, len);
}
responseBody = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inReader != null) {
inReader.close();
}
if (in != null) {
in.close();
}
}
return responseBody;
}
public static String doGet(String requestURL, Map<String, String> requestPropertyMap) throws IOException {
BufferedReader inReader = null;
InputStream in = null;
String responseBody = "";
try {
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(timeOut);
conn.setReadTimeout(timeOut);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
if (!requestPropertyMap.isEmpty()) {
for (String key : requestPropertyMap.keySet()) {
conn.setRequestProperty(key, requestPropertyMap.get(key));
}
}
conn.connect();
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
in = conn.getInputStream();
} else {
in = conn.getErrorStream();
}
inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
int len;
char[] tmp = new char[256];
while ((len = inReader.read(tmp)) > 0) {
sb.append(tmp, 0, len);
}
responseBody = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inReader != null) {
inReader.close();
}
if (in != null) {
in.close();
}
}
return responseBody;
}
public static String doGet(String requestURL, String username, String password) throws IOException {
BufferedReader inReader = null;
InputStream in = null;
String responseBody = "";
try {
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(timeOut);
conn.setReadTimeout(timeOut);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
Base64.Encoder encoder = Base64.getEncoder();
String encode = encoder.encodeToString((username + ":" + password).getBytes());
conn.setRequestProperty("Authorization", "Basic " + encode);
conn.connect();
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
in = conn.getInputStream();
} else {
in = conn.getErrorStream();
}
inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
int len;
char[] tmp = new char[256];
while ((len = inReader.read(tmp)) > 0) {
sb.append(tmp, 0, len);
}
responseBody = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inReader != null) {
inReader.close();
}
if (in != null) {
in.close();
}
}
return responseBody;
}
public static String doGet(String requestURL, Map<String, String> requestPropertyMap, String username, String password) throws IOException {
BufferedReader inReader = null;
InputStream in = null;
String responseBody = "";
try {
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(timeOut);
conn.setReadTimeout(timeOut);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
if (!requestPropertyMap.isEmpty()) {
for (String key : requestPropertyMap.keySet()) {
conn.setRequestProperty(key, requestPropertyMap.get(key));
}
}
Base64.Encoder encoder = Base64.getEncoder();
String encode = encoder.encodeToString((username + ":" + password).getBytes());
conn.setRequestProperty("Authorization", "Basic " + encode);
conn.connect();
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
in = conn.getInputStream();
} else {
in = conn.getErrorStream();
}
inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
int len;
char[] tmp = new char[256];
while ((len = inReader.read(tmp)) > 0) {
sb.append(tmp, 0, len);
}
responseBody = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inReader != null) {
inReader.close();
}
if (in != null) {
in.close();
}
}
return responseBody;
}
四·POST请求封装代码:
private static int timeOut = 60000;
public static String doPost(String requestURL, String body) throws IOException {
BufferedReader inReader = null;
InputStream in = null;
String responseBody = "";
OutputStream outputStream = null;
BufferedWriter writer = null;
try {
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(timeOut);
conn.setReadTimeout(timeOut);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.connect();
outputStream = conn.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
writer.write(body);
writer.flush();
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
in = conn.getInputStream();
} else {
in = conn.getErrorStream();
}
inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
int len;
char[] tmp = new char[256];
while ((len = inReader.read(tmp)) > 0) {
sb.append(tmp, 0, len);
}
responseBody = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.close();
}
if (outputStream != null) {
outputStream.close();
}
if (inReader != null) {
inReader.close();
}
if (in != null) {
in.close();
}
}
return responseBody;
}
public static String doPost(String requestURL, String body, String username, String password) throws IOException {
BufferedReader inReader = null;
InputStream in = null;
String responseBody = "";
OutputStream outputStream = null;
BufferedWriter writer = null;
try {
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(timeOut);
conn.setReadTimeout(timeOut);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
Base64.Encoder encoder = Base64.getEncoder();
String encode = encoder.encodeToString((username + ":" + password).getBytes());
conn.setRequestProperty("Authorization", "Basic " + encode);
conn.connect();
outputStream = conn.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
writer.write(body);
writer.flush();
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
in = conn.getInputStream();
} else {
in = conn.getErrorStream();
}
inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
int len;
char[] tmp = new char[256];
while ((len = inReader.read(tmp)) > 0) {
sb.append(tmp, 0, len);
}
responseBody = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.close();
}
if (outputStream != null) {
outputStream.close();
}
if (inReader != null) {
inReader.close();
}
if (in != null) {
in.close();
}
}
return responseBody;
}