Example usage for org.springframework.mock.http.client MockClientHttpRequest MockClientHttpRequest

List of usage examples for org.springframework.mock.http.client MockClientHttpRequest MockClientHttpRequest

Introduction

In this page you can find the example usage for org.springframework.mock.http.client MockClientHttpRequest MockClientHttpRequest.

Prototype

public MockClientHttpRequest(HttpMethod httpMethod, URI uri) 

Source Link

Document

Create an instance with the given HttpMethod and URI.

Usage

From source file:io.spring.initializr.web.test.MockMvcClientHttpRequestFactory.java

@Override
public ClientHttpRequest createRequest(final URI uri, final HttpMethod httpMethod) throws IOException {
    return new MockClientHttpRequest(httpMethod, uri) {
        @Override/*from  w  w  w .  j a v  a  2  s .c  om*/
        public ClientHttpResponse executeInternal() throws IOException {
            try {
                MockHttpServletRequestBuilder requestBuilder = request(httpMethod, uri.toString());
                requestBuilder.content(getBodyAsBytes());
                requestBuilder.headers(getHeaders());
                MockHttpServletResponse servletResponse = actions(requestBuilder).andReturn().getResponse();
                HttpStatus status = HttpStatus.valueOf(servletResponse.getStatus());
                if (status.value() >= 400) {
                    requestBuilder = request(HttpMethod.GET, "/error")
                            .requestAttr(RequestDispatcher.ERROR_STATUS_CODE, status.value())
                            .requestAttr(RequestDispatcher.ERROR_REQUEST_URI, uri.toString());
                    if (servletResponse.getErrorMessage() != null) {
                        requestBuilder.requestAttr(RequestDispatcher.ERROR_MESSAGE,
                                servletResponse.getErrorMessage());
                    }
                    // Overwrites the snippets from the first request
                    servletResponse = actions(requestBuilder).andReturn().getResponse();
                }
                byte[] body = servletResponse.getContentAsByteArray();
                HttpHeaders headers = getResponseHeaders(servletResponse);
                MockClientHttpResponse clientResponse = new MockClientHttpResponse(body, status);
                clientResponse.getHeaders().putAll(headers);
                return clientResponse;
            } catch (Exception ex) {
                throw new IllegalStateException(ex);
            }
        }

    };
}