我们如何将java对象传递到groovyx.net.http.RestClient的POST调用

时间:2018-10-12 09:25:59

标签: java spock rest-client

我已经编写了一个Restfull网络服务POST api调用,该api接受java object作为请求参数

示例代码:

@POST
@Path("/sample")
@ApiOperation(value = "insert sample data",
        notes = "insert sample data", response = SampleRequest.class)
public Response processSampleData(@ApiParam(value = "SampleRequest", required = true) SampleRequest sampleRequest) {
   //code to insert data
}

我正在编写集成测试方法,但无法将java object传递给RestClient

样本测试方法:

def "process sample data"(){
    when:
    /*String json = '{"sampleDataList":[{ "name": "test1", "id": "12345" },{ "name": "test2", "id": "123456"}]}'*/
    Sample sample= new Sample();
    sample.setName("test1");
    sample.setId("12345");
    SampleRequest reqObj = new SampleRequest();
    reqObj.getSampleList().add(sample);

    //tried with json
    /*HttpResponseDecorator response = getRestClient().post([path: "$BASE_URL"+"/sample", body: json])*/

    //tried with java object also
    HttpResponseDecorator response = getRestClient().post([path: "$BASE_URL"+"/sample", body: SampleRequest])

    then:
    response
}

我尝试同时使用jsonjava object,但没有一个对我有用。遇到No encoder found for request content type */*错误

1 个答案:

答案 0 :(得分:1)

当我添加contentType: "application/json时,它适用于json的身体类型。

我改变了

HttpResponseDecorator response = getRestClient().post([path: "$BASE_URL"+"/sample",body: json])

收件人

HttpResponseDecorator response = getRestClient().post([path: "$BASE_URL"+"/sample",contentType: "application/json" ,body: json])