Spring中的内容类型问题

时间:2016-09-08 08:21:49

标签: java spring http-headers

我收到的POST有问题。我有以下端点:

@RequestMapping(value = "/payment", method = POST)
public void saveOrder(@RequestBody PaymentDto paymentDto) throws RequiredFieldException, IOException, MessagingException {
//do something
}

现在,当有人向我发送此网址的POST时,我会收到以下回复:

{"errorMessage":"Unsupported Media Type",
"errorId":"906f5dc8-0b79-4f91-9eaa-a252e8d5ac76",
"errorDetails":
    {"message":"Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported",
    "exception":"org.springframework.web.HttpMediaTypeNotSupportedException",
    "errors":null
}}

我该如何解决?发送时我无法更改内容类型标题。它是从我无法控制的服务器发送的。

3 个答案:

答案 0 :(得分:1)

到目前为止,对我来说最好的替代方法是编写一个转换器

我选择这种方式的要点是:

  • 我只需要处理我的API中的一个端点(也只有一个对象),这与我可以控制它们的其他端点不同;
  • 我无法控制调用我的端点的第三方服务;
  • 第三方服务仅通过一种方式通过媒体类型为application/x-www-form-urlencoded的POST调用我的服务。

第一:编写一个对象

package xx.xx.xx;

import java.io.Serializable;

public class MyObject implements Serializable {

    private static final long serialVersionUID = -7474838713815803531L;

    private String name;

    private String id;

    ...

    getters

    setters

    ...

}

第二:创建一个转换器以映射模型

package xx.xx.xx;

import java.io.IOException;
import java.util.Map;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import com.fasterxml.jackson.databind.ObjectMapper;

import xx.xx.xx.MyObject;

public class MyObjectConverter extends AbstractHttpMessageConverter<MyObject> {

    private static final FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    protected boolean supports(Class<?> clazz) {
        return (MyObject.class == clazz);
    }

    @Override
    protected MyObject readInternal(Class<? extends MyObject> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        Map<String, String> vals = formHttpMessageConverter.read(null, inputMessage).toSingleValueMap();
        return mapper.convertValue(vals, MyObject.class);
    }

    @Override
    protected void writeInternal(MyObject myObject, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

    }
}

第三:告诉Spring使用此转换器

package xx.xx.xx;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class HppResponseConverterDTOConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(converter());
    }

    private MyObjectConverter converter() {
        MyObjectConverter converter = new MyObjectConverter();
        MediaType mediaType = new MediaType("application", "x-www-form-urlencoded", Charset.forName("UTF-8"));
        converter.setSupportedMediaTypes(Arrays.asList(mediaType));
        return converter;
    }
}

奖金:此配置/实现处理属性内的下划线字符,换句话说:您可以使用@JsonProperty注释,因为上面的实现使用ObjectMapper并且对象Mapper(我认为)与春天用Content-type: application/json序列化普通POST。

第四,最后:使用此实现:

package xx.xx.xx;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/my-object-controller")
public class MyObjectController {

    @PostMapping(value = "/something", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public void doSomething(@RequestBody MyObject myObject) {
        doSomethingWithMyObject(myObject);
    }

}

我希望这会有所帮助:)

编辑:我正在使用Spring Boot 2

答案 1 :(得分:0)

实际上,有助于将@RequestBody更改为@ModelAttribute。所以我的代码看起来像那样:

@RequestMapping(value = "/payment", method = POST)
public void saveOrder(@ModelAttribute PaymentDto paymentDto) throws RequiredFieldException, IOException, MessagingException {
//do something
}

答案 2 :(得分:0)

如果Content Type是application / json或application / xml使用@RequestBody注释,如果是application / x-www-form-urlencoded则使用@ModelAttribute