如何使用HttpPost传递包含其他自定义对象列表的对象来调用REST服务

时间:2017-11-01 16:35:58

标签: java json rest http-post

我试图通过将object作为参数传递来调用REST服务,该参数包含其他自定义对象的列表。我收到“错误405:不支持请求方法POST”错误。 客户端代码 -

CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(SSLConnectionSocketFactory.getSystemSocketFactory()).build();

        httpPost = new HttpPost("http://api100.abc.xyz.com:9080/abcd/api/sscws/v1/saveContributions");
        httpPost.addHeader(WebAppConstants.CONTENT_TYPE, WebAppConstants.APPLICATION_JSON);
        httpPost.addHeader(WebAppConstants.ACCEPT, WebAppConstants.APPLICATION_JSON);
        httpPost.addHeader(WebAppConstants.X_USERNAME, userContext.getUserID());
        httpPost.addHeader(WebAppConstants.X_ENTERPRISE_ID, "123456");
        httpPost.addHeader(WebAppConstants.X_UNIQUE_ID, "A548742ATG");  //to do

        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        String requestParamJson = ow.writeValueAsString(contribRequestParamDto);

        httpPost.setEntity(new StringEntity(contribRequestParamDto, WebAppConstants.UTF_8));

在上面的代码中,contribRequestParamDto是ContributionsRequestParamDto类的一个对象,它将看起来像这样 -

public class ContributionsRequestParamDto {

private String tokenID;
private String taxID;
private String affiliateID;
private long planID;
private String accountNumber;
private String bankAccountNumber;
private String transitId;
private BigDecimal eftAmt;
private Date ppeDate;
private String taxYear;
private Short planType;

private List<ParticipantsDeferralDto> participantsDeferrals;
private List<EmployersContributionDto> employersContributions;

}

REST端点将如下所示 -

 @Transactional
@RestController
@RequestMapping("/v1")
@Api(value="v1", description="")
public class SscRestController {
    @RequestMapping(value="/saveContributions", 
            method=RequestMethod.POST, produces={MediaType.APPLICATION_JSON_VALUE}, consumes={MediaType.APPLICATION_JSON_VALUE})
    @ApiOperation(value="Returns the saved contributions object")
    public String saveContributions(@RequestBody ContributionsRequestParam contributionsParam) throws Exception {
        return "success";
    }
}

Json请求正文是 -

{
      "tokenID" : "123456789",
      "taxID" : "123456",
      "affiliateID" : "123456789",
      "planID" : 123456,
      "ppeDate" : "2017-10-24",
      "taxYear" : "2017",
      "planType" : 1,
      "participantsDeferrals" : [ {
        "taxId" : "555555",
        "participantDeferralAmt" : 22.00
      } ],
      "employersContributions" : [ {
        "taxId" : "555555",
        "employerContributionAmt" : 22.00
      } ]
    }

这不起作用,因为我收到“错误405:不支持请求方法POST”错误。如果通过从“ContributionsRequestParamDto”对象中删除那些列表字段,从JSON请求体中删除“participantDeferrals”和“employerContributions”的列表字段,它将起作用。所以我确信自定义对象列表及其对应的JSON请求体有问题。我在这里错过了什么吗?请帮忙。谢谢!

1 个答案:

答案 0 :(得分:0)

我更改了日期的类型。现在它是普通的String而不是SQL日期。在对象中将其类型更改为字符串后,它正常工作