休息保证 - 无法使用参数和正文进行POST

时间:2012-08-23 23:18:27

标签: java rest rest-assured

我正在使用Rest Assured测试REST api。尝试使用url和body内容中的参数进行POST时,我遇到了错误。这在手动测试时可以正常工作。从网址中删除参数不是一个选项

测试代码:

String endpoint = http://localhost:8080/x/y/z/id?custom=test;
String body = "[{\"boolField\":true,\"intField\":991},
                {\"boolField\":false,\"intField\":998}]";
expect().spec(OK).given().body(body).post(endpoint);

运行时会抛出以下错误

You can either send parameters OR body content in the POST, not both!

java.lang.IllegalStateException: You can either send parameters OR body content in the POST, not both!
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:77)
at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrapNoCoerce.callConstructor(ConstructorSite.java:102)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:198)
at com.jayway.restassured.internal.RequestSpecificationImpl.sendRequest(RequestSpecificationImpl.groovy:282)
at com.jayway.restassured.internal.RequestSpecificationImpl.this$2$sendRequest(RequestSpecificationImpl.groovy)
at com.jayway.restassured.internal.RequestSpecificationImpl$this$2$sendRequest.callCurrent(Unknown Source)
at com.jayway.restassured.internal.RequestSpecificationImpl.post(RequestSpecificationImpl.groovy:83)
...

为什么Rest Assured不允许POST中的参数和正文内容?

3 个答案:

答案 0 :(得分:27)

您需要将参数指定为queryParameter而不是“param”或​​“parameter”。 POST的Param将默认形成在请求正文中发送的参数。

given().
        queryParam("name, "value").
        body(..).
when().
        post(..);

答案 1 :(得分:0)

我不太熟悉放心,但你应该能够将这些参数移到身体上。这就是典型的POST参数的工作原理。将参数作为请求URL的一部分通常仅针对GET进行。也许尝试将“custom = test”作为身体的第一行?

答案 2 :(得分:0)

您必须将参数指定为queryParam。这是一个例子:

RequestSpecification request=new RequestSpecBuilder().build();
ResponseSpecification response=new ResponseSpecBuilder().build();
@Test
public void test(){
  User user=new User();
  given()
  .spec(request)
  .queryParam(query_param1_name, query_param1_name_value)
  .queryParam(query_param2_name, query_param2_name_value)
  .contentType(ContentType.JSON)
  .body(user)
  .post(API_ENDPOINT)
  .then()
  .statusCode(200).log().all();

}