【发布时间】:2021-02-04 09:57:19
【问题描述】:
我知道如何从邮递员上传多部分文件,但如何通过 REST API 来做同样的事情。当我通过邮递员时,消费者 API 工作正常,但在通过 REST 做同样的事情时,它不起作用。
我正在通过这样的 REST 做同样的事情,但它不起作用:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body
= new LinkedMultiValueMap<>();
body.add("file", file);
HttpEntity<MultiValueMap<String, Object>> requestEntity
= new HttpEntity<>(body, headers);
String serverUrl = "http://localhost:9001/communication/api/messageEngine/event/RECIPT/sendEmailAttachment";
ParameterizedTypeReference<ApiResponse<Map<String,Object>>> parameterizedTypeReference =
new ParameterizedTypeReference<com.loylty.dataacquisition.model.ApiResponse<Map<String,Object>>>() {};
RestTemplate restTemplate = new RestTemplate();
try {
ResponseEntity<com.loylty.dataacquisition.model.ApiResponse<Map<String,Object>>> result =
restTemplate.exchange(serverUrl, HttpMethod.POST, requestEntity, parameterizedTypeReference);
if (result.getStatusCode().is2xxSuccessful() == false) {
throw new DENotReachableException();
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
目标 API 或消费者 API:
@CrossOrigin
@RequestMapping(method = RequestMethod.POST, value = "/event/{event}/sendEmailAttachment", consumes = {"multipart/form-data"})
public ApiResponse<Object> sendReceiptWithAttachment(@RequestPart("file") MultipartFile file, @PathVariable("event") String event) {
LidsysUtil.messageId.set(String.valueOf(new Date().getTime()));
MessageTracker tracker = new MessageTracker(LidsysUtil.messageId.get(), event);
LidsysUtil.tracker.set(tracker);
LOGGER.info("Executing Message Id : {} ", LidsysUtil.messageId.get());
LOGGER.info("Request received for event : {}", event);
// LOGGER.info("Request Body : {}", LidsysUtil.displayJSON(requestBody));
Map<String, Object> request = messageEngineService.initiateEmailwithAttachmentV2( file, event);
return new ApiResponse<>(APIResponseKey.ALL_GOOD, messageEngineService.execute(request, event), null);
}
当我尝试使用 REST api 时出现以下异常
源微服务异常
020-10-21 19:11:18,237 [ERROR]---[DirectJDKLog.java]---[http-nio-8010-exec-2]: Servlet.service() for servlet [dispatcherServlet] in context with path [/dataacquisition] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException: 400 null] with root cause
org.springframework.web.client.HttpClientErrorException: 400 null
目标微服务异常
2020-10-21 19:11:17,445 [ERROR]---[HttpLoggingFilter.java]---[http-nio-9001-exec-10]: null
【问题讨论】:
-
当你说它不起作用时,它是否会打印出任何有意义的信息来帮助理解问题?像个例外?
-
@EvrisTzam 是的,它可以打印,但没有多大帮助。
-
请更新您的问题并添加它。
-
@EvrisTzam 更新异常
标签: java rest file-upload multipartform-data