HTTP 请求工具类 HTTPUtils
,其中涉及 HTTP 请求相关的各种操作,关于这些方法详细的介绍可以查看这些博客
💬相关
博客文章《Java发起HTTP请求并解析JSON返回数据》
https://blog.csdn.net/weixin_42077074/article/details/128672130
博客文章《Java发起同异步HTTP请求和处理数据》
https://blog.csdn.net/weixin_42077074/article/details/129601132
博客文章《JavaJSON处理工具类JSONUtils》
https://blog.csdn.net/weixin_42077074/article/details/129364274
HTTP 请求工具类 HTTPUtils
包含的属性和方法
headers
:请求头示例disableSSLVerification()
:禁用 SSL 验证addHeadersToRequest()
:将请求头添加到 HTTP 请求中concatParamsToURL()
:将请求参数拼接进 URLrequestHTTPContent()
:发起 HTTP 请求并获取响应内容asyncHTTPRequest()
:异步 HTTP 请求readResponseContent()
:读取响应内容outputResponseContent()
:输出响应内容printJSON()
:打印 JSONprintXML()
:打印 XMLviewImage()
:浏览图像
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import javax.imageio.ImageIO;
import javax.net.ssl.*;
import javax.swing.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
public class HTTPUtils {
public static Map<String, String> headers = new HashMap<String, String>() {{
put("Accept", "application/json");
put("Content-Type", "application/json;charset=UTF-8");
put("charset", "UTF-8");
put("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
}};
public static void disableSSLVerification() {
try {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
public static void addHeadersToRequest(HttpURLConnection httpConn, Map<String, ?> headers) {
if (headers != null) {
for (Map.Entry<String, ?> entry : headers.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value.getClass().isArray()) {
for (Object v : (Object[]) value) {
httpConn.setRequestProperty(key, v.toString());
}
} else {
httpConn.setRequestProperty(key, value.toString());
}
}
}
}
public static String concatParamsToURL(String staticURL, String paramsStr){
return staticURL + paramsStr;
}
public static String concatParamsToURL(String staticURL, Map<String, ?> params) throws Exception {
if (params.isEmpty()) {
return staticURL;
}
StringBuilder sb = new StringBuilder(staticURL);
boolean hasParams = staticURL.indexOf("?") != -1;
for (Map.Entry<String, ?> entry : params.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value.getClass().isArray()) {
for (Object v : (Object[]) value) {
sb.append(hasParams ? "&" : "?")
.append(URLEncoder.encode(key, "utf-8"))
.append("=")
.append(URLEncoder.encode(v.toString(), "utf-8"));
hasParams = true;
}
} else {
sb.append(hasParams ? "&" : "?")
.append(URLEncoder.encode(key, "utf-8"))
.append("=")
.append(URLEncoder.encode(value.toString(), "utf-8"));
hasParams = true;
}
}
return sb.toString();
}
public static String requestHTTPContent(String strURL) throws Exception {
return requestHTTPContent(strURL, "GET", null, null);
}
public static String requestHTTPContent(String strURL, String method) throws Exception {
return requestHTTPContent(strURL, method, null, null);
}
public static String requestHTTPContent(String strURL, String method, Map<String, ?> headers) throws Exception {
return requestHTTPContent(strURL, method, headers, null);
}
public static String requestHTTPContent(String strURL, String method, Map<String, ?> headers, Map<String, ?> params) throws Exception {
disableSslVerification();
if(method.equals("GET") && params != null) {
strURL = concatParamsToURL(strURL, params);
}
System.out.println(strURL);
URL url = new URL(strURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod(method);
addHeadersToRequest(httpConn, headers);
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
if(method.equals("POST") && params!=null) {
OutputStream out = new DataOutputStream(httpConn.getOutputStream());
out.write(JSON.toJSONString(params).getBytes("UTF-8"));
out.flush();
}
else{
httpConn.connect();
}
String contentType = httpConn.getContentType();
String result = readResponseContent(httpConn);
return result;
}
public static CompletableFuture<String> asyncHTTPRequest(String strURL, String method, Map<String, ?> headers, Map<String, ?> params) {
return CompletableFuture.supplyAsync(() -> {
try {
return requestHTTPContent(strURL, method, headers, params);
} catch (Exception e) {
e.printStackTrace();
return null;
}
});
}
public static String readResponseContent(HttpURLConnection httpConn) throws Exception {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()))) {
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
}
public static void outputResponseContent(String responseContent, String contentType) throws Exception {
if (contentType.contains("application/json")) {
JSONObject jsonObj = JSON.parseObject(responseContent);
printJSON(jsonObj,0);
}
else if (contentType.contains("application/xml")) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(responseContent)));
printXML(doc);
}
else if (contentType.contains("image/jpeg") || contentType.contains("image/png")) {
byte[] imageBytes = responseContent.getBytes();
ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
BufferedImage image = ImageIO.read(bis);
viewImage(new ImageIcon(image));
}
else if (contentType.contains("application/pdf")) {
System.out.println("[PDF document]");
}
else if (contentType.contains("application/octet-stream")) {
System.out.println("[Binary data]");
}
else if (contentType.contains("text/html") || contentType.contains("text/plain")) {
System.out.println(responseContent);
}
else {
System.out.println(responseContent);
}
}
public static void printJSON(JSONObject jsonObj, int level) {
if (jsonObj != null) {
for (Map.Entry<String, Object> entry : jsonObj.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
String indent = String.join("", Collections.nCopies(level, "\t"));
if (value instanceof JSONObject) {
System.out.println(indent + key + " = {");
printJSON((JSONObject) value, level + 1);
System.out.println(indent + "}");
} else {
System.out.println(indent + key + " = " + value.toString());
}
}
}
}
public static void printXML(Document doc) {
Element root = doc.getDocumentElement();
printXML(System.out, root, 0);
}
private static void printXML(PrintStream ps, Element element, int indent) {
printTrunk(ps, indent);
ps.printf("├─ 元素: %s\n", element.getNodeName());
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Attr attribute = (Attr) attributes.item(i);
printTrunk(ps, indent + 1);
ps.printf("├─ 属性: %s = %s\n", attribute.getName(), attribute.getValue());
}
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
printXML(ps, (Element) child, indent + 1);
} else if (child.getNodeType() == Node.TEXT_NODE) {
String text = child.getNodeValue().trim();
if (!text.isEmpty()) {
printTrunk(ps, indent + 1);
ps.printf("└─ 文本: %s\n", text);
}
}
}
}
private static void printTrunk(PrintStream ps, int indent) {
for (int i = 0; i < indent; i++) {
ps.print("| ");
}
}
private static void viewImage(ImageIcon imageIcon) {
JLabel label = new JLabel(imageIcon);
JFrame frame = new JFrame("图片显示");
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)