【问题标题】:Spring Boot Produces text/csv, Could not find acceptable representationSpring Boot 生成文本/csv,找不到可接受的表示
【发布时间】:2017-01-24 20:58:11
【问题描述】:

我正在尝试让我的 Spring Boot 应用程序返回 accept=text/csv,我继续得到:

org.springframework.web.HttpMediaTypeNotAcceptableException: 不能 找到可接受的代表

我已添加:

compile "com.fasterxml.jackson.dataformat:jackson-dataformat-xml:${jackson_version}"
compile "com.fasterxml.jackson.dataformat:jackson-dataformat-csv:${jackson_version}"

致我的build.gradle,我使用 SpringMVC

处理程序看起来像:

@RequestMapping(value = "/{id}/csv", method = RequestMethod.GET, produces = "text/csv")
    public List<RegistrationCode> exportToCsv(@ApiParam(name = "id", required = true, value = "string") @PathVariable String id, HttpServletResponse response) {

...
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"",
        csvFileName);
    response.setHeader(headerKey, headerValue);
    response.setContentType("text/csv;charset=utf-8");
    return registrationCodes;
}

卷曲示例:

curl -X GET --header 'Accept: text/csv' --header 'Authorization: Bearer ...' 'http://localhost:8080/api/1001/csv'

消息转换器:

public class CsvMessageConverter extends AbstractHttpMessageConverter<List<RegistrationCode>> {

}

添加消息转换的示例(传统的applicationContext.xml):

<util:list id="messageConverters">
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"
          p:objectMapper-ref="jsonObjectMapperFactory"/>
    <!--bean class="org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter"
          p:objectMapper-ref="xmlObjectMapperFactory"/-->
    <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
    <bean class="com.binding.CsvMessageConverter"/>
</util:list>

【问题讨论】:

  • 我们用邮递员测试过
  • @GaëlMarziou 完成了我的信息已转换(我只是无法注册)我会发布它的标题。
  • 我不知道你可以在不使用 Spring MVC 的情况下使用 @RequestMapping。有什么好处?你不能把 springfox 也用于招摇,对吧?
  • @GaëlMarziou 正确,添加 @EnableWebMvc 或扩展 WebMvcConfigurationSupport 因为大多数答案都暗示了我的申请。
  • 对不起,我帮不上忙,你离 JHipster 生成的代码还很远。

标签: spring jhipster


【解决方案1】:
    //Adding the message converter
@Configuration
public class MyApplicationConfiguration {
    ...    
    @Bean
    public HttpMessageConverters customConverters() {
        return new HttpMessageConverters(new CsvMessageConverter());
    }
}

我可以在这里找到一些注册转换的说明:

In Spring Boot, adding a custom converter by extending MappingJackson2HttpMessageConverter seems to overwrite the existing converter

【讨论】:

    猜你喜欢
    • 2017-10-18
    • 2019-01-23
    • 2015-04-12
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 2022-10-20
    • 2014-04-18
    相关资源
    最近更新 更多