0
我正在开发基于HAL的REST API和Spring引导。我在我的控制器中需要一个端点,它将文件发送到客户端。有对SO一些例子,但它不会因为以下异常的工作:基于HAL的REST API和下载文件端点
Resolved exception caused by Handler execution:
org.springframework.http.converter.HttpMessageNotWritableException: Could not write
content: No serializer found for class java.io.ByteArrayInputStream and no properties
discovered to create BeanSerializer (to avoid exception, disable
SerializationFeature.FAIL_ON_EMPTY_BEANS) through reference chain:
org.springframework.core.io.ByteArrayResource["inputStream"]);
nested exception is com.fasterxml.jackson.databind.JsonMappingException:
No serializer found for class java.io.ByteArrayInputStream
and no properties discovered to create BeanSerializer (to avoid exception,
disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain:
org.springframework.core.io.ByteArrayResource["inputStream"])
我的Spring应用程序:
@EnableHypermediaSupport(type = HAL)
@SpringBootApplication
public class MyServer {
public static String CURIE_NAMESPACE = "myNS";
public @Bean
CurieProvider curieProvider() {
return new DefaultCurieProvider(CURIE_NAMESPACE, new UriTemplate("/docs/html5/{rel}.html"));
}
@Bean
public HttpMessageConverters customConverters() {
ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
return new HttpMessageConverters(arrayHttpMessageConverter);
}
public static void main(String[] args) {
SpringApplication.run(MyServer.class, args);
}
}
我的控制器类看起来是这样的:
@BasePathAwareController
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MyController implements ResourceProcessor<RepositoryLinksResource> {
public static final String ENDPOINT_URL = "/myResource";
...
@RequestMapping(value = ENDPOINT_URL + "/download", method = RequestMethod.GET)
public ResponseEntity<ByteArrayResource> downloadAttachment(){
...
// get from my service the resource
MyClass myResource = myService.getResource();
String filename = myResource.getFilename();
String contentType = myResource.getContentType();
try (InputStream myStream = myResource.getStream()) {
HttpHeaders respHeaders = new HttpHeaders();
respHeaders.setContentType(MediaType.valueOf(contentType));
respHeaders.setContentDispositionFormData("attachment", filename);
byte[] bytes = IOUtils.toByteArray(myStream);
ByteArrayResource byteResource = new ByteArrayResource(bytes);
return ResponseEntity.ok()
.headers(respHeaders)
.contentType(MediaType.parseMediaType(contentType))
.body(byteResource);
} catch (Exception e) {
...
}
}
}
我正在添加自定义转换器bean,如我的应用程序代码所示。但我认为这是因为这是@EnableHypermediaSupport is not compatible with Spring Boot's Jackson2ObjectMapperBuilder #333它不工作!?
弹簧引导版本:1.5.2.RELEASE
弹簧HATEOAS版本:0.23.0.RELEASE
任何想法?
您的建议没有任何工作......但谢谢。 – Oni1