在spring mvc中POST字符串期间获得400 Bad Request

时间:2015-04-02 08:37:20

标签: spring spring-mvc post http-headers bad-request

我有一个休息api,在POST中接受一个String并返回一个对象,

这是方法:

@RequestMapping(method = RequestMethod.POST, value = "/aValue", headers = "Accept=application/json")
public @ResponseBody
MyObject getMyObject(@RequestBody String string) {

    MyObject response = myService.getMyObject(string);
    return response;
}

现在当我从其他服务调用api时,例如,如果我这样做POST,它总是给我400 Bad Request:

    List<Object> providers = new ArrayList<Object>();
    providers.add(jsonProvider);

    WebClient client = WebClient.create(baseUrl + myAPI, providers);

    client.type(MediaType.APPLICATION_JSON);
    client.accept(MediaType.APPLICATION_JSON);

    MyObject response = client.post(userId, MyObject.class);

    return response;

而不是我使用的工作解决方案是这个:

MyObject response = client.post("\"" + userId + "\"", MyObject.class);
有人能帮帮我吗?谢谢你们

1 个答案:

答案 0 :(得分:0)

您遇到问题'因为您发布的内容不是有效的JSON,但您表明它在您的客户端代码中。由于您似乎只传递了一个简单的字符串属性 userId ,您可以通过添加consumes = "text/plain"

来简单地更改映射以接收纯文本
  @RequestMapping(method = RequestMethod.POST, value = "/aValue", headers = "Accept=application/json", consumes = "text/plain")
public @ResponseBody
MyObject getMyObject(@RequestBody String string) {

让您的客户发送纯文本,所以

client.type(MediaType.TEXT_PLAIN);