package sendMQTT.HTTPUtils;
|
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import java.io.*;
|
import java.net.HttpURLConnection;
|
import java.net.URL;
|
import java.net.URLEncoder;
|
import java.nio.charset.StandardCharsets;
|
import java.util.Properties;
|
|
/**
|
* Properties文件上传工具类
|
* 将Properties文件转换为JSON并上传到服务器
|
*/
|
public class PropertiesFileUploader {
|
|
private static final String DEFAULT_UPLOAD_URL = "http://39.99.43.227:8866/api/file/upload";
|
private static final String DEFAULT_FILENAME = "dikuai";
|
private static final int CONNECT_TIMEOUT = 30000; // 30秒连接超时
|
private static final int READ_TIMEOUT = 60000; // 60秒读取超时
|
|
|
/**
|
* 将Properties文件转换为JSON字符串
|
* @param filePath Properties文件路径
|
* @return JSON字符串
|
* @throws Exception 如果读取或转换失败
|
*/
|
public static String propertiesFileToJson(String filePath) throws Exception {
|
Properties props = new Properties();
|
InputStream inputStream = null;
|
|
try {
|
File file = new File(filePath);
|
if (!file.exists() || !file.isFile()) {
|
throw new Exception("文件不存在或不是有效文件: " + filePath);
|
}
|
|
inputStream = new FileInputStream(file);
|
props.load(inputStream);
|
|
// 使用Jackson将Properties转换为JSON字符串
|
ObjectMapper objectMapper = new ObjectMapper();
|
// Properties本质上是一个Map<String, String>,可以直接序列化为JSON
|
String json = objectMapper.writeValueAsString(props);
|
|
return json;
|
} finally {
|
if (inputStream != null) {
|
inputStream.close();
|
}
|
}
|
}
|
|
/**
|
* 生成毫秒级时间戳
|
* @return 当前时间的毫秒级时间戳(自1970年1月1日UTC以来的毫秒数)
|
*/
|
public static long getCurrentTimestamp() {
|
return System.currentTimeMillis();
|
}
|
|
/**
|
* 移动路径发送方法
|
*
|
* @param mes_id 消息唯一标识
|
* @param user_id 用户ID
|
* @param device_id 设备编号
|
* @param propertiesFilePath Properties文件路径
|
* @return JSON字符串
|
* @throws Exception 当上传或转换失败时抛出
|
*/
|
public static String movePathSend(String mes_id, String user_id, String device_id, String propertiesFilePath) {
|
// 上传Properties文件
|
FileUploadResponse fileUploadResponse = PropertiesFileUploader.uploadPropertiesFile(propertiesFilePath);
|
if (fileUploadResponse == null) {
|
return null;
|
}
|
|
/* // 打印上传响应信息
|
System.out.println("文件上传响应信息:");
|
System.out.println("├─ 消息内容: " + fileUploadResponse.getMessage());
|
System.out.println("├─ 原始文件名: " + fileUploadResponse.getFilename());
|
System.out.println("├─ 保存文件名: " + fileUploadResponse.getSavedFilename());
|
System.out.println("├─ 文件类型: " + fileUploadResponse.getFileType());
|
System.out.println("├─ 文件大小: " + fileUploadResponse.getSize());
|
System.out.println("├─ 下载地址: " + fileUploadResponse.getDownloadUrl());
|
System.out.println("├─ 文件UUID: " + fileUploadResponse.getUuid());
|
System.out.println("└─ 文件哈希: " + (fileUploadResponse.getHexString() != null ? fileUploadResponse.getHexString() : "N/A"));*/
|
|
// 构建数据对象
|
MovePathCommand.MovePathData pathData = new MovePathCommand.MovePathData(
|
fileUploadResponse.getSavedFilename(), // filename
|
fileUploadResponse.getSize(), // filesize
|
fileUploadResponse.getDownloadUrl() // url
|
);
|
long timestamp = PropertiesFileUploader.getCurrentTimestamp();
|
// 构建命令对象
|
MovePathCommand command = new MovePathCommand(
|
mes_id,
|
timestamp,
|
user_id,
|
device_id,
|
pathData
|
);
|
|
// 转换为JSON字符串
|
ObjectMapper objectMapper = new ObjectMapper();
|
String jsonString = null;
|
try {
|
jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(command);
|
} catch (JsonProcessingException e) {
|
return null;
|
}
|
|
return jsonString;
|
}
|
|
|
|
|
/**
|
* 上传Properties文件到服务器
|
*
|
* @param filePath Properties文件路径
|
* @param filename 文件名(用于URL参数,默认为"dikuai")
|
* @param uploadUrl 上传接口URL(可选,默认使用文档中的URL)
|
* @return FileUploadResponse 上传响应结果
|
* @throws Exception 当上传失败时抛出
|
*/
|
public static FileUploadResponse uploadPropertiesFile(String filePath, String filename, String uploadUrl) throws Exception {
|
// 参数校验
|
if (filePath == null || filePath.trim().isEmpty()) {
|
throw new IllegalArgumentException("文件路径不能为空");
|
}
|
|
// 使用默认值
|
if (filename == null || filename.trim().isEmpty()) {
|
filename = DEFAULT_FILENAME;
|
}
|
if (uploadUrl == null || uploadUrl.trim().isEmpty()) {
|
uploadUrl = DEFAULT_UPLOAD_URL;
|
}
|
|
// 调用Server.propertiesFileToJson方法生成JSON字符串
|
String jsonData = propertiesFileToJson(filePath);
|
|
// 构建完整的URL(包含filename参数,进行URL编码)
|
String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8.name());
|
String fullUrl = uploadUrl + "?filename=" + encodedFilename;
|
|
// 发送HTTP POST请求
|
HttpURLConnection connection = createConnection(fullUrl);
|
|
try {
|
// 发送JSON数据
|
try (OutputStream outputStream = connection.getOutputStream()) {
|
byte[] jsonBytes = jsonData.getBytes(StandardCharsets.UTF_8);
|
outputStream.write(jsonBytes);
|
outputStream.flush();
|
}
|
|
// 获取响应
|
String responseJson = getResponse(connection);
|
|
// 解析响应JSON
|
ObjectMapper objectMapper = new ObjectMapper();
|
FileUploadResponse response = objectMapper.readValue(responseJson, FileUploadResponse.class);
|
|
return response;
|
|
} finally {
|
if (connection != null) {
|
connection.disconnect();
|
}
|
}
|
}
|
|
/**
|
* 上传Properties文件到服务器(使用默认参数)
|
*
|
* @param filePath Properties文件路径
|
* @return FileUploadResponse 上传响应结果
|
* @throws Exception 当上传失败时抛出
|
*/
|
public static FileUploadResponse uploadPropertiesFile(String filePath) {
|
try {
|
return uploadPropertiesFile(filePath, DEFAULT_FILENAME, DEFAULT_UPLOAD_URL);
|
} catch (Exception e) {
|
return null;
|
}
|
}
|
|
/**
|
* 上传Properties文件到服务器(指定文件名)
|
*
|
* @param filePath Properties文件路径
|
* @param filename 文件名(用于URL参数)
|
* @return FileUploadResponse 上传响应结果
|
* @throws Exception 当上传失败时抛出
|
*/
|
public static FileUploadResponse uploadPropertiesFile(String filePath, String filename) throws Exception {
|
return uploadPropertiesFile(filePath, filename, DEFAULT_UPLOAD_URL);
|
}
|
|
/**
|
* 创建HTTP连接
|
*/
|
private static HttpURLConnection createConnection(String urlString) throws Exception {
|
URL url = new URL(urlString);
|
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
|
// 设置连接属性
|
connection.setDoOutput(true);
|
connection.setDoInput(true);
|
connection.setUseCaches(false);
|
connection.setRequestMethod("POST");
|
connection.setConnectTimeout(CONNECT_TIMEOUT);
|
connection.setReadTimeout(READ_TIMEOUT);
|
|
// 设置请求头
|
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
|
connection.setRequestProperty("Accept", "application/json");
|
connection.setRequestProperty("User-Agent", "PropertiesFileUploader/1.0");
|
|
return connection;
|
}
|
|
/**
|
* 获取服务器响应
|
*/
|
private static String getResponse(HttpURLConnection connection) throws Exception {
|
// 检查HTTP响应码
|
int status = connection.getResponseCode();
|
InputStream inputStream;
|
|
if (status >= 200 && status < 300) {
|
inputStream = connection.getInputStream();
|
} else {
|
inputStream = connection.getErrorStream();
|
}
|
|
// 读取响应内容
|
StringBuilder response = new StringBuilder();
|
try (BufferedReader reader = new BufferedReader(
|
new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
|
String line;
|
while ((line = reader.readLine()) != null) {
|
response.append(line);
|
}
|
}
|
|
// 如果请求失败,抛出异常
|
if (status >= 400) {
|
throw new Exception("HTTP请求失败,状态码: " + status + ",响应: " + response.toString());
|
}
|
|
return response.toString();
|
}
|
|
/**
|
* 安全上传方法(不抛出异常,返回结果对象)
|
*
|
* @param filePath Properties文件路径
|
* @param filename 文件名(用于URL参数,可选)
|
* @param uploadUrl 上传接口URL(可选)
|
* @return UploadResult 包含上传结果的封装对象
|
*/
|
public static UploadResult uploadPropertiesFileSafe(String filePath, String filename, String uploadUrl) {
|
try {
|
FileUploadResponse response = uploadPropertiesFile(filePath, filename, uploadUrl);
|
ObjectMapper objectMapper = new ObjectMapper();
|
String responseJson = objectMapper.writeValueAsString(response);
|
return new UploadResult(true, response.getMessage(), responseJson, 200);
|
} catch (Exception e) {
|
return new UploadResult(false, "上传失败: " + e.getMessage(), null, 500);
|
}
|
}
|
|
/**
|
* 安全上传方法(使用默认参数)
|
*
|
* @param filePath Properties文件路径
|
* @return UploadResult 包含上传结果的封装对象
|
*/
|
public static UploadResult uploadPropertiesFileSafe(String filePath) {
|
return uploadPropertiesFileSafe(filePath, DEFAULT_FILENAME, DEFAULT_UPLOAD_URL);
|
}
|
|
/**
|
* 上传结果封装类
|
*/
|
public static class UploadResult {
|
private boolean success;
|
private String message;
|
private String data;
|
private int statusCode;
|
|
public UploadResult(boolean success, String message, String data, int statusCode) {
|
this.success = success;
|
this.message = message;
|
this.data = data;
|
this.statusCode = statusCode;
|
}
|
|
public boolean isSuccess() {
|
return success;
|
}
|
|
public String getMessage() {
|
return message;
|
}
|
|
public String getData() {
|
return data;
|
}
|
|
public int getStatusCode() {
|
return statusCode;
|
}
|
|
@Override
|
public String toString() {
|
return "UploadResult{" +
|
"success=" + success +
|
", message='" + message + '\'' +
|
", data='" + data + '\'' +
|
", statusCode=" + statusCode +
|
'}';
|
}
|
}
|
}
|