【发布时间】:2017-10-17 10:27:51
【问题描述】:
我正在使用 Spring Boot 开发基于 HAL 的 REST API。我的控制器中需要一个端点,它将文件发送到客户端。 SO上有一些示例,但由于以下异常,它不起作用:
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 它不起作用!?
spring-boot 版本:1.5.2.RELEASE
spring-hateoas 版本:0.23.0.RELEASE
有什么想法吗?
【问题讨论】:
标签: java spring rest spring-boot spring-hateoas