【发布时间】:2019-06-21 09:15:24
【问题描述】:
我有一个控制器应该允许下载具有任意内容类型的文件:
@GetMapping(value="/download/{directory}/{name}",
consumes=MediaType.ALL_VALUE)
@Timed
public ResponseEntity<byte[]> downloadFile(@PathVariable String directory,
@PathVariable String name) {
log.debug("REST request to download File : {}/{}", directory, name);
byte[] content = "it works".getBytes();
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, "text/plain");
return new ResponseEntity<>(content, headers, HttpStatus.OK);
}
我想在这样的单元测试中进行测试:
...
private MockMvc restFileMockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final FileResource fileResource = new FileResource(fileService);
this.restFileMockMvc = MockMvcBuilders.standaloneSetup(fileResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator).build();
}
@Test
@Transactional
public void downloadFile() throws Exception {
String url = "/api/download/it/works.txt";
restFileMockMvc.perform(get(url).header(HttpHeaders.ACCEPT, "*/*"))
.andDo(MockMvcResultHandlers.print()) // Debugging only!
.andExpect(status().isOk());
}
但显然,内容类型存在问题。接受标头。 MockMvcResultHandlers.print() 产生以下内容:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /api/download/DIRDIR/NAMENAME
Parameters = {}
Headers = {Accept=[*/*]}
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type = com.example.storage.web.rest.FileResource
Method = public org.springframework.http.ResponseEntity<byte[]> com.example.storage.web.rest.FileResource.downloadFile(java.lang.String,java.lang.String)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.HttpMediaTypeNotAcceptableException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 406
Error message = null
Headers = {Content-Type=[application/problem+json]}
Content type = application/problem+json
Body = {"type":"https://www.jhipster.tech/problem/problem-with-message","title":"Not Acceptable","status":406,"detail":"Could not find acceptable representation","path":"/api/download/DIRDIR/NAMENAME","message":"error.http.406"}
Forwarded URL = null
Redirected URL = null
Cookies = []
看起来请求是使用Accept: */* 发送的。 Spring 抱怨什么?
【问题讨论】:
-
您没有
Content-Type标头,只有Accept标头。 -
@M. Deinum
Content-Type是响应头,Accept是请求头。 -
Content-Type既是请求又是响应。 -
但这是一个获取请求。它没有身体。
-
它仍然需要标题。从
@RequstMapping中删除consumes部分。
标签: spring spring-mvc