This commit is contained in:
砂糖
2025-10-08 10:09:48 +08:00
parent 524c8343e6
commit f40d6ffcb6

View File

@@ -65,29 +65,33 @@ public class HttpYoloDetector implements YoloDetector {
}
try {
// 将OpenCV的Mat转换为JPEG字节数组
BytePointer buffer = new BytePointer();
imencode(".jpg", bgr, buffer);
byte[] jpgBytes = new byte[(int)(buffer.capacity())];
buffer.get(jpgBytes);
buffer.deallocate();
// 准备HTTP请求参数
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
// 1. 添加文件参数(正确)
// 仅发送文件model_name 放到查询参数
body.add("file", new CustomByteArrayResource(jpgBytes, "image.jpg"));
// 2. 添加 model_name 作为表单参数(关键修改)
body.add("model_name", modelName); // 直接添加到表单数据中
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
// 不需要拼接查询参数直接使用原始API URL
String url = apiUrl;
// 将 model_name 作为查询参数
String urlWithQuery;
try {
String encoded = java.net.URLEncoder.encode(modelName, java.nio.charset.StandardCharsets.UTF_8.toString());
urlWithQuery = apiUrl + (apiUrl.contains("?") ? "&" : "?") + "model_name=" + encoded;
} catch (Exception ex) {
urlWithQuery = apiUrl + (apiUrl.contains("?") ? "&" : "?") + "model_name=" + modelName;
}
// 发送请求
ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
// 发送请求到Python服务
ResponseEntity<String> response = restTemplate.postForEntity(urlWithQuery, requestEntity, String.class);
String responseBody = response.getBody();
if (!response.getStatusCode().is2xxSuccessful()) {
log.error("HTTP检测失败: status={}, body={}", response.getStatusCodeValue(), responseBody);