Spring Controller中的Post方法请求正文

时间:2019-04-19 09:19:40

标签: java spring rest post pojo

我需要实现一个接受对象(json)的发布端点。但是对象中的某些参数是可选的。因此,当我尝试进行api调用时,它没有映射到相应的方法。

该页面显示找不到页面Err:404

我发送的请求正文仅包含两个字段,其余均为可选字段。

对象的Pojo

public class Post {
  private String owner;

  private String activity;

  private Boolean edited;

  private String clientApp;

  private String serviceProvider;

  private long id;

  private Text text;

  public static class Text {

    private String text;

    public String getText() {
      return text;
    }

    public void setText(String text) {
      this.text = text;
    }
  }

  public String getOwner() {
    return owner;
  }

  public void setOwner(String owner) {
    this.owner = owner;
  }

  public String getActivity() {
    return activity;
  }

  public void setActivity(String activity) {
    this.activity = activity;
  }

  public Boolean getEdited() {
    return edited;
  }

  public void setEdited(Boolean edited) {
    this.edited = edited;
  }

  public String getClientApp() {
    return clientApp;
  }

  public void setClientApp(String clientApp) {
    this.clientApp = clientApp;
  }

  public String getServiceProvider() {
    return serviceProvider;
  }

  public void setServiceProvider(String serviceProvider) {
    this.serviceProvider = serviceProvider;
  }

  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public Text getText() {
    return text;
  }

  public void setText(Text text) {
    this.text = text;
  }

}

Spring控制器:

@RequestMapping(method = RequestMethod.POST, value="/publish/post",consumes = MediaType.APPLICATION_JSON_VALUE)
    public String publish(
      @RequestBody Post map) {
      logger.info("Post method")
      return "Completed";
    }

卷曲命令:

curl -X POST \
  http://localhost:4569/rest/publish/post \
  -H 'Content-Type: application/json' \  
  -d '{
    "owner": "Owner of the Company",
    "text": {
        "text": "Png new image"
    }
}'

有效载荷

{
"owner": "Owner of the Company",
"text": {
    "text": "Png new image"
}

}

其他控制器:

@RestController
@RequestMapping("/rest")
public class SocialController {

    private static final Logger logger = LoggerFactory.getLogger(SocialController.class);

    @RequestMapping(method = RequestMethod.POST, value="/publish/post",consumes = MediaType.APPLICATION_JSON_VALUE)
    public String publish(
      @RequestBody Post map) {
      logger.info("Post method")
      return "Completed";
    }
}

1 个答案:

答案 0 :(得分:0)

您在URL中缺少应用程序根目录 http://localhost:4569/[App-name]/rest/publish/post

pojo中的可选字段在调用rest方法方面没有问题。