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