All Downloads are FREE. Search and download functionalities are using the official Maven repository.
Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
com.soento.core.util.HttpUtil Maven / Gradle / Ivy
package com.soento.core.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
/**
* http 工具类
*
* @author soento
*/
public class HttpUtil {
private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
public static String get(String url) {
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = null;
try {
log.info("URL : {}", url);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("GET");
// 建立实际的连接
connection.connect();
// 遍历所有的响应头字段
logHeader(connection);
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String result = "";
String getLine;
while ((getLine = in.readLine()) != null) {
result += getLine;
}
log.info("↓↓↓↓↓↓ RESPONSE ↓↓↓↓↓↓");
log.info(result);
log.info("↑↑↑↑↑↑ RESPONSE ↑↑↑↑↑↑");
return result;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
StreamUtil.close(in);
}
}
private static void logHeader(HttpURLConnection connection) {
// 获取所有响应头字段
Map> headers = connection.getHeaderFields();
// 遍历所有的响应头字段
log.info("↓↓↓↓↓↓ HEAD ↓↓↓↓↓↓");
for (String key : headers.keySet()) {
log.info("{} : {}", key, headers.get(key));
}
log.info("↑↑↑↑↑↑ HEAD ↑↑↑↑↑↑");
}
private static void logParams(String params) {
if (StringUtil.isNotBlank(params)) {
log.info("↓↓↓↓↓↓ REQUEST ↓↓↓↓↓↓");
log.info(params);
log.info("↑↑↑↑↑↑ REQUEST ↑↑↑↑↑↑");
}
}
private static void logFiles(File[] files) {
if (files != null && files.length > 0) {
log.info("↓↓↓↓↓↓ FILE ↓↓↓↓↓↓");
for (File file : files) {
log.info(file.getPath());
}
log.info("↑↑↑↑↑↑ FILE ↑↑↑↑↑↑");
}
}
public static String convertParams(Map params) {
StringBuilder result = new StringBuilder();
for (String key : params.keySet()) {
result.append(key);
result.append("=");
result.append(params.get(key));
result.append("&");
}
return result.toString();
}
public static String post(String url, String contentType, String params) {
// 得到请求的输出流对象
DataOutputStream out = null;
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = null;
try {
log.info("URL : {}", url);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
// 设置通用的请求属性
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
if (StringUtil.isNotBlank(params)) {
// 得到请求的输出流对象
out = new DataOutputStream(connection.getOutputStream());
out.write(params.getBytes(StandardCharsets.UTF_8));
out.flush();
}
// 建立实际的连接
connection.connect();
// 遍历所有的响应头字段
logHeader(connection);
logParams(params);
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String result = "";
String getLine;
while ((getLine = in.readLine()) != null) {
result += getLine;
}
log.info("↓↓↓↓↓↓ RESPONSE ↓↓↓↓↓↓");
log.info(result);
log.info("↑↑↑↑↑↑ RESPONSE ↑↑↑↑↑↑");
return result;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
StreamUtil.close(out);
StreamUtil.close(in);
}
}
public static String post(String url, String params) {
return post(url, "application/x-www-form-urlencoded", params);
}
public static String postJson(String url, String params) {
return post(url, "application/json", params);
}
public static String upload(String url, File[] files, String params) {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
// 得到请求的输出流对象
DataOutputStream out = null;
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = null;
try {
log.info("URL : {}", url);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
// 设置是否从httpUrlConnection读入,默认情况下是true;
connection.setDoInput(true);
// 设置是否向httpUrlConnection输出
connection.setDoOutput(true);
// Post 请求不能使用缓存
connection.setUseCaches(false);
// 设定请求的方法,默认是GET
connection.setRequestMethod("POST");
// 设置字符编码连接参数
connection.setRequestProperty("Connection", "Keep-Alive");
// 设置字符编码
connection.setRequestProperty("Charset", "UTF-8");
// 设置请求内容类型
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// 设置DataOutputStream
out = new DataOutputStream(connection.getOutputStream());
if (StringUtil.isNotBlank(params)) {
String[] paramKV = params.split("&");
for (String kv : paramKV) {
String[] tmp = kv.split("=");
if (tmp.length == 2) {
String k = tmp[0];
String v = tmp[1];
if (StringUtil.isNotBlank(k) && StringUtil.isNotBlank(v)) {
out.writeBytes(twoHyphens + boundary + end);
out.writeBytes("Content-Disposition: form-data; " + "name=\"" + k + "\"" + end);
out.writeBytes(end);
out.write(v.getBytes(StandardCharsets.UTF_8));
out.writeBytes(end);
}
}
}
}
if (files != null && files.length > 0) {
for (int i = 0; i < files.length; i++) {
File file = files[i];
String uploadFile = file.getPath();
String filename = uploadFile.substring(uploadFile.lastIndexOf("//") + 1);
out.writeBytes(twoHyphens + boundary + end);
out.writeBytes("Content-Disposition: form-data; " + "name=\"file" + i + "\";filename=\"" + filename + "\"" + end);
out.writeBytes(end);
out.write(FileUtil.readFileToByteArray(file));
out.writeBytes(end);
}
}
out.writeBytes(twoHyphens + boundary + twoHyphens + end);
out.flush();
// 建立实际的连接
connection.connect();
// 遍历所有的响应头字段
logHeader(connection);
logParams(params);
logFiles(files);
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String result = "";
String getLine;
while ((getLine = in.readLine()) != null) {
result += getLine;
}
in.close();
log.info("↓↓↓↓↓↓ RESPONSE ↓↓↓↓↓↓");
log.info(result);
log.info("↑↑↑↑↑↑ RESPONSE ↑↑↑↑↑↑");
return result;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
StreamUtil.close(out);
StreamUtil.close(in);
}
}
public static File download(String url, String path) {
File file = null;
BufferedInputStream in = null;
OutputStream out = null;
try {
log.debug("URL : {}", url);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
// 设定请求的方法,默认是GET
connection.setRequestMethod("GET");
// 设置字符编码
connection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
connection.connect();
// 文件大小
int fileLength = connection.getContentLength();
log.debug("FILE LENGTH : {}", fileLength);
// 文件名
String filePath = connection.getURL().getFile();
log.debug("FILE PATH : {}", filePath);
String fileName = filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1);
log.debug("FILE NAME : {}", fileName);
in = new BufferedInputStream(connection.getInputStream());
file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
out = new FileOutputStream(file);
int size = 0;
byte[] buf = new byte[1024];
while ((size = in.read(buf)) != -1) {
out.write(buf, 0, size);
}
out.flush();
log.debug("↓↓↓↓↓↓ RESPONSE ↓↓↓↓↓↓");
log.debug(file.getPath());
log.debug("↑↑↑↑↑↑ RESPONSE ↑↑↑↑↑↑");
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
StreamUtil.close(out);
StreamUtil.close(in);
}
return file;
}
}