本文整理了Java中org.mockserver.model.HttpRequest.withBody()
方法的一些代码示例,展示了HttpRequest.withBody()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpRequest.withBody()
方法的具体详情如下:
包路径:org.mockserver.model.HttpRequest
类名称:HttpRequest
方法名:withBody
[英]The exact string body to match on such as "this is an exact string body"
[中]要匹配的精确字符串正文,例如“这是一个精确的字符串正文”
代码示例来源:origin: jamesdbloom/mockserver
private void setBody(HttpRequest httpRequest, HttpServletRequest httpServletRequest) {
byte[] bodyBytes = IOStreamUtils.readInputStreamToByteArray(httpServletRequest);
if (bodyBytes.length > 0) {
if (ContentTypeMapper.isBinary(httpServletRequest.getHeader(CONTENT_TYPE.toString()))) {
httpRequest.withBody(new BinaryBody(bodyBytes));
} else {
Charset requestCharset = ContentTypeMapper.getCharsetFromContentTypeHeader(httpServletRequest.getHeader(CONTENT_TYPE.toString()));
httpRequest.withBody(new StringBody(new String(bodyBytes, requestCharset), DEFAULT_HTTP_CHARACTER_SET.equals(requestCharset) ? null : requestCharset));
}
}
}
代码示例来源:origin: jamesdbloom/mockserver
private void setBody(HttpRequest httpRequest, FullHttpRequest fullHttpRequest) {
if (fullHttpRequest.content() != null && fullHttpRequest.content().readableBytes() > 0) {
byte[] bodyBytes = new byte[fullHttpRequest.content().readableBytes()];
fullHttpRequest.content().readBytes(bodyBytes);
if (bodyBytes.length > 0) {
if (ContentTypeMapper.isBinary(fullHttpRequest.headers().get(CONTENT_TYPE))) {
httpRequest.withBody(new BinaryBody(bodyBytes));
} else {
Charset requestCharset = ContentTypeMapper.getCharsetFromContentTypeHeader(fullHttpRequest.headers().get(CONTENT_TYPE));
httpRequest.withBody(new StringBody(new String(bodyBytes, requestCharset), DEFAULT_HTTP_CHARACTER_SET.equals(requestCharset) ? null : requestCharset));
}
}
}
}
}
代码示例来源:origin: jamesdbloom/mockserver
/**
* Clear all expectations and logs that match the http
*
* @param httpRequest the http request that is matched against when deciding whether to clear each expectation if null all expectations are cleared
*/
public MockServerClient clear(HttpRequest httpRequest) {
sendRequest(request().withMethod("PUT").withPath(calculatePath("clear")).withBody(httpRequest != null ? httpRequestSerializer.serialize(httpRequest) : "", StandardCharsets.UTF_8));
return clientClass.cast(this);
}
代码示例来源:origin: jamesdbloom/mockserver
/**
* Clear expectations, logs or both that match the http
*
* @param httpRequest the http request that is matched against when deciding whether to clear each expectation if null all expectations are cleared
* @param type the type to clear, EXPECTATION, LOG or BOTH
*/
public MockServerClient clear(HttpRequest httpRequest, ClearType type) {
sendRequest(request().withMethod("PUT").withPath(calculatePath("clear")).withQueryStringParameter("type", type.name().toLowerCase()).withBody(httpRequest != null ? httpRequestSerializer.serialize(httpRequest) : "", StandardCharsets.UTF_8));
return clientClass.cast(this);
}
代码示例来源:origin: jamesdbloom/mockserver
/**
* Verify a list of requests have been sent in the order specified for example:
* <pre>
* mockServerClient
* .verify(
* request()
* .withPath("/first_request")
* .withBody("some_request_body"),
* request()
* .withPath("/second_request")
* .withBody("some_request_body")
* );
* </pre>
*
* @param httpRequests the http requests that must be matched for this verification to pass
* @throws AssertionError if the request has not been found
*/
public MockServerClient verify(HttpRequest... httpRequests) throws AssertionError {
if (httpRequests == null || httpRequests.length == 0 || httpRequests[0] == null) {
throw new IllegalArgumentException("verify(HttpRequest...) requires a non null non empty array of HttpRequest objects");
}
VerificationSequence verificationSequence = new VerificationSequence().withRequests(httpRequests);
String result = sendRequest(request().withMethod("PUT").withPath(calculatePath("verifySequence")).withBody(verificationSequenceSerializer.serialize(verificationSequence), StandardCharsets.UTF_8)).getBodyAsString();
if (result != null && !result.isEmpty()) {
throw new AssertionError(result);
}
return clientClass.cast(this);
}
代码示例来源:origin: jamesdbloom/mockserver
/**
* Verify no requests have been have been sent.
*
* @throws AssertionError if any request has been found
*/
public MockServerClient verifyZeroInteractions() throws AssertionError {
Verification verification = verification().withRequest(request()).withTimes(exactly(0));
String result = sendRequest(request().withMethod("PUT").withPath(calculatePath("verify")).withBody(verificationSerializer.serialize(verification), StandardCharsets.UTF_8)).getBodyAsString();
if (result != null && !result.isEmpty()) {
throw new AssertionError(result);
}
return clientClass.cast(this);
}
代码示例来源:origin: jamesdbloom/mockserver
@Test
public void shouldReturnErrorForInvalidRequest() throws Exception {
// when
HttpResponse httpResponse = httpClient.sendRequest(
request()
.withMethod("PUT")
.withHeader(HOST.toString(), "localhost:" + this.getServerPort())
.withPath(addContextToPath("mockserver/clear"))
.withBody("{" + NEW_LINE +
" \"path\" : 500," + NEW_LINE +
" \"method\" : true," + NEW_LINE +
" \"keepAlive\" : \"false\"" + NEW_LINE +
" }")
).get(10, TimeUnit.SECONDS);
// then
assertThat(httpResponse.getStatusCode(), is(400));
assertThat(httpResponse.getBodyAsString(), is("3 errors:" + NEW_LINE +
" - instance type (string) does not match any allowed primitive type (allowed: [\"boolean\"]) for field \"/keepAlive\"" + NEW_LINE +
" - instance type (boolean) does not match any allowed primitive type (allowed: [\"string\"]) for field \"/method\"" + NEW_LINE +
" - instance type (integer) does not match any allowed primitive type (allowed: [\"string\"]) for field \"/path\""));
}
}
代码示例来源:origin: jamesdbloom/mockserver
@Test
public void shouldReturnErrorForInvalidRequestToVerify() throws Exception {
// when
org.mockserver.model.HttpResponse httpResponse = new NettyHttpClient(clientEventLoopGroup, null).sendRequest(
request()
.withMethod("PUT")
.withHeader(HOST.toString(), "localhost:" + getProxyPort())
.withPath(addContextToPath("mockserver/verify"))
.withBody("{" + NEW_LINE +
" \"httpRequest\": {" + NEW_LINE +
" \"path\": \"/simple\"" + NEW_LINE +
" }, " + NEW_LINE +
" \"times\": 1" + NEW_LINE +
"}")
).get(10, TimeUnit.SECONDS);
// then
assertThat(httpResponse.getStatusCode(), Is.is(400));
assertThat(httpResponse.getBodyAsString(), Is.is("1 error:" + NEW_LINE +
" - instance type (integer) does not match any allowed primitive type (allowed: [\"object\"]) for field \"/times\""));
}
代码示例来源:origin: jamesdbloom/mockserver
@Test
public void shouldReturnErrorForInvalidRequestToVerifySequence() throws Exception {
// when
org.mockserver.model.HttpResponse httpResponse = new NettyHttpClient(clientEventLoopGroup, null).sendRequest(
request()
.withMethod("PUT")
.withHeader(HOST.toString(), "localhost:" + getProxyPort())
.withPath(addContextToPath("mockserver/verifySequence"))
.withBody("{" + NEW_LINE +
" \"httpRequest\": {" + NEW_LINE +
" \"path\": false" + NEW_LINE +
" }," + NEW_LINE +
" \"httpRequest\": {" + NEW_LINE +
" \"path\": 10" + NEW_LINE +
" }" + NEW_LINE +
"}")
).get(10, TimeUnit.SECONDS);
// then
assertThat(httpResponse.getStatusCode(), Is.is(400));
assertThat(httpResponse.getBodyAsString(), Is.is("1 error:" + NEW_LINE +
" - object instance has properties which are not allowed by the schema: [\"httpRequest\"]"));
}
}
代码示例来源:origin: jamesdbloom/mockserver
@Test
public void shouldReturnErrorForInvalidRequestToClear() throws Exception {
// when
org.mockserver.model.HttpResponse httpResponse = new NettyHttpClient(clientEventLoopGroup, null).sendRequest(
request()
.withMethod("PUT")
.withHeader(HOST.toString(), "localhost:" + getProxyPort())
.withPath(addContextToPath("mockserver/clear"))
.withBody("{" + NEW_LINE +
" \"path\" : 500," + NEW_LINE +
" \"method\" : true," + NEW_LINE +
" \"keepAlive\" : \"false\"" + NEW_LINE +
" }")
).get(10, TimeUnit.SECONDS);
// then
assertThat(httpResponse.getStatusCode(), Is.is(400));
assertThat(httpResponse.getBodyAsString(), Is.is("3 errors:" + NEW_LINE +
" - instance type (string) does not match any allowed primitive type (allowed: [\"boolean\"]) for field \"/keepAlive\"" + NEW_LINE +
" - instance type (boolean) does not match any allowed primitive type (allowed: [\"string\"]) for field \"/method\"" + NEW_LINE +
" - instance type (integer) does not match any allowed primitive type (allowed: [\"string\"]) for field \"/path\""));
}
代码示例来源:origin: jamesdbloom/mockserver
@Override
public HttpRequest handle(HttpRequest httpRequest) {
return request()
.withHeader("Host", "localhost:" + httpRequest.getFirstHeader("x-echo-server-port"))
.withHeader("x-test", httpRequest.getFirstHeader("x-test"))
.withBody("some_overridden_body")
.withSecure(httpRequest.isSecure());
}
}
代码示例来源:origin: jamesdbloom/mockserver
@Test
public void shouldReturnErrorForInvalidExpectation() throws Exception {
// when
HttpResponse httpResponse = httpClient.sendRequest(
request()
.withMethod("PUT")
.withHeader(HOST.toString(), "localhost:" + this.getServerPort())
.withPath(addContextToPath("mockserver/expectation"))
.withBody("{" + NEW_LINE +
" \"httpRequest\" : {" + NEW_LINE +
" \"path\" : \"/path_one\"" + NEW_LINE +
" }," + NEW_LINE +
" \"incorrectField\" : {" + NEW_LINE +
" \"body\" : \"some_body_one\"" + NEW_LINE +
" }," + NEW_LINE +
" \"times\" : {" + NEW_LINE +
" \"remainingTimes\" : 1" + NEW_LINE +
" }," + NEW_LINE +
" \"timeToLive\" : {" + NEW_LINE +
" \"unlimited\" : true" + NEW_LINE +
" }" + NEW_LINE +
"}")
).get(10, TimeUnit.SECONDS);
// then
assertThat(httpResponse.getStatusCode(), is(400));
assertThat(httpResponse.getBodyAsString(), is("2 errors:" + NEW_LINE +
" - object instance has properties which are not allowed by the schema: [\"incorrectField\"]" + NEW_LINE +
" - oneOf of the following must be specified [\"httpResponse\", \"httpResponseTemplate\", \"httpResponseObjectCallback\", \"httpResponseClassCallback\", \"httpForward\", \"httpForwardTemplate\", \"httpForwardObjectCallback\", \"httpForwardClassCallback\", \"httpOverrideForwardedRequest\", \"httpError\"] but 0 found"));
}
代码示例来源:origin: jamesdbloom/mockserver
/**
* Bind new ports to listen on
*/
public List<Integer> bind(Integer... ports) {
String boundPorts = sendRequest(request().withMethod("PUT").withPath(calculatePath("bind")).withBody(portBindingSerializer.serialize(portBinding(ports)), StandardCharsets.UTF_8)).getBodyAsString();
return portBindingSerializer.deserialize(boundPorts).getPorts();
}
代码示例来源:origin: jamesdbloom/mockserver
void sendExpectation(Expectation expectation) {
HttpResponse httpResponse = sendRequest(request().withMethod("PUT").withPath(calculatePath("expectation")).withBody(expectation != null ? expectationSerializer.serialize(expectation) : "", StandardCharsets.UTF_8));
if (httpResponse != null && httpResponse.getStatusCode() != 201) {
throw new ClientException(formatLogMessage("error:{}while submitted expectation:{}", httpResponse.getBody(), expectation));
}
}
代码示例来源:origin: jamesdbloom/mockserver
/**
* Retrieve the logs associated to a specific requests, this shows all logs for expectation matching, verification, clearing, etc
*
* @param httpRequest the http request that is matched against when deciding whether to return each request, use null for the parameter to retrieve for all requests
* @return all log messages recorded by the MockServer when creating expectations, matching expectations, performing verification, clearing logs, etc
*/
public String retrieveLogMessages(HttpRequest httpRequest) {
HttpResponse httpResponse = sendRequest(
request()
.withMethod("PUT")
.withPath(calculatePath("retrieve"))
.withQueryStringParameter("type", RetrieveType.LOGS.name())
.withBody(httpRequest != null ? httpRequestSerializer.serialize(httpRequest) : "", StandardCharsets.UTF_8)
);
return httpResponse.getBodyAsString();
}
代码示例来源:origin: jamesdbloom/mockserver
public HttpRequest buildObject() {
return new HttpRequest()
.withMethod(method)
.withPath(path)
.withQueryStringParameters(queryStringParameters)
.withBody((body != null ? Not.not(body.buildObject(), body.getNot()) : null))
.withHeaders(headers)
.withCookies(cookies)
.withSecure(secure)
.withKeepAlive(keepAlive);
}
代码示例来源:origin: jamesdbloom/mockserver
/**
* Retrieve the recorded requests that match the httpRequest parameter, use null for the parameter to retrieve all requests
*
* @param httpRequest the http request that is matched against when deciding whether to return each request, use null for the parameter to retrieve for all requests
* @param format the format to retrieve the expectations, either JAVA or JSON
* @return an array of all requests that have been recorded by the MockServer in the order they have been received and including duplicates where the same request has been received multiple times
*/
public String retrieveRecordedRequests(HttpRequest httpRequest, Format format) {
HttpResponse httpResponse = sendRequest(
request()
.withMethod("PUT")
.withPath(calculatePath("retrieve"))
.withQueryStringParameter("type", RetrieveType.REQUESTS.name())
.withQueryStringParameter("format", format.name())
.withBody(httpRequest != null ? httpRequestSerializer.serialize(httpRequest) : "", StandardCharsets.UTF_8)
);
return httpResponse.getBodyAsString();
}
代码示例来源:origin: jamesdbloom/mockserver
/**
* Retrieve the active expectations match the httpRequest parameter, use null for the parameter to retrieve all expectations
*
* @param httpRequest the http request that is matched against when deciding whether to return each expectation, use null for the parameter to retrieve for all requests
* @param format the format to retrieve the expectations, either JAVA or JSON
* @return an array of all expectations that have been setup and have not expired
*/
public String retrieveActiveExpectations(HttpRequest httpRequest, Format format) {
HttpResponse httpResponse = sendRequest(
request()
.withMethod("PUT")
.withPath(calculatePath("retrieve"))
.withQueryStringParameter("type", RetrieveType.ACTIVE_EXPECTATIONS.name())
.withQueryStringParameter("format", format.name())
.withBody(httpRequest != null ? httpRequestSerializer.serialize(httpRequest) : "", StandardCharsets.UTF_8)
);
return httpResponse.getBodyAsString();
}
}
代码示例来源:origin: jamesdbloom/mockserver
/**
* Retrieve the request-response combinations that have been recorded as a list of expectations, only those that match the httpRequest parameter are returned, use null to retrieve all requests
*
* @param httpRequest the http request that is matched against when deciding whether to return each request, use null for the parameter to retrieve for all requests
* @param format the format to retrieve the expectations, either JAVA or JSON
* @return an array of all expectations that have been recorded by the MockServer in the order they have been received and including duplicates where the same request has been received multiple times
*/
public String retrieveRecordedExpectations(HttpRequest httpRequest, Format format) {
HttpResponse httpResponse = sendRequest(
request()
.withMethod("PUT")
.withPath(calculatePath("retrieve"))
.withQueryStringParameter("type", RetrieveType.RECORDED_EXPECTATIONS.name())
.withQueryStringParameter("format", format.name())
.withBody(httpRequest != null ? httpRequestSerializer.serialize(httpRequest) : "", StandardCharsets.UTF_8)
);
return httpResponse.getBodyAsString();
}
代码示例来源:origin: jamesdbloom/mockserver
public HttpRequest clone() {
return not(request(), not)
.withMethod(method)
.withPath(path)
.withQueryStringParameters(getQueryStringParameters().clone())
.withBody(body)
.withHeaders(getHeaders().clone())
.withCookies(getCookies().clone())
.withKeepAlive(keepAlive)
.withSecure(secure);
}
内容来源于网络,如有侵权,请联系作者删除!