List of usage examples for org.springframework.http.client ClientHttpResponse getRawStatusCode
int getRawStatusCode() throws IOException;
From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.ApiResponseErrorHandlerTest.java
/** * Tests {@link ApiResponseErrorHandler#handleError} in the case where the error response body is in an unsupported * media type, e.g. an HTML error page returned by an intermediate web proxy. * /*from w w w.j av a 2 s . co m*/ * @throws Exception If an unexpected error occurs. */ @Test public void testHandleErrorWhenResponseBodyInUnsupportedMediaType() throws Exception { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.TEXT_HTML); String body = "<html><head>Error</head><body>Woz error</body>"; ClientHttpResponse response = this.createMockClientHttpResponse(HttpStatus.GATEWAY_TIMEOUT, httpHeaders, body); EasyMock.replay(response); try { this.errorHandler.handleError(response); fail("Expected exception to be thrown for error response."); } catch (ApiErrorResponseException e) { ApiError apiError = null; ApiErrorResponseException expectedException = new ApiErrorResponseException(response.getRawStatusCode(), null, httpHeaders, null, body.getBytes(), apiError); assertApiErrorResponseException(expectedException, e); } }
From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.ApiResponseErrorHandlerTest.java
/** * Tests {@link ApiResponseErrorHandler#handleError} in the case where the error response body contains an * unexpected entity in a supported media type. * /* w ww . jav a 2s .co m*/ * @throws Exception If an unexpected error occurs. */ @Test public void testHandleErrorWhenResponseBodyContainsUnexpectedEntity() throws Exception { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_XML); String body = "<?xml version='1.0' encoding='UTF-8'?><notAnApiError><foo>1</foo></notAnApiError>"; ClientHttpResponse response = this.createMockClientHttpResponse(HttpStatus.GATEWAY_TIMEOUT, httpHeaders, body); EasyMock.replay(response); try { this.errorHandler.handleError(response); fail("Expected exception to be thrown for error response."); } catch (ApiErrorResponseException e) { ApiError apiError = null; ApiErrorResponseException expectedException = new ApiErrorResponseException(response.getRawStatusCode(), null, httpHeaders, null, body.getBytes(), apiError); assertApiErrorResponseException(expectedException, e); } }
From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.ApiResponseErrorHandlerTest.java
/** * Tests {@link ApiResponseErrorHandler#handleError} in the case where the error response body is empty, e.g. because * it is returned by an intermediate web proxy. * /*from ww w.j a v a 2s . c o m*/ * @throws Exception If an unexpected error occurs. */ @Test public void testHandleErrorWhenResponseBodyEmpty() throws Exception { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentLength(0); String body = null; ClientHttpResponse response = this.createMockClientHttpResponse(HttpStatus.GATEWAY_TIMEOUT, httpHeaders, body); EasyMock.replay(response); try { this.errorHandler.handleError(response); fail("Expected exception to be thrown for error response."); } catch (ApiErrorResponseException e) { ApiError apiError = null; ApiErrorResponseException expectedException = new ApiErrorResponseException(response.getRawStatusCode(), null, httpHeaders, null, new byte[0], apiError); assertApiErrorResponseException(expectedException, e); } }
From source file:org.spring.data.gemfire.rest.GemFireRestInterfaceTest.java
@SuppressWarnings("deprecation") private RestTemplate setErrorHandler(final RestTemplate restTemplate) { restTemplate.setErrorHandler(new ResponseErrorHandler() { private final Set<HttpStatus> errorStatuses = new HashSet<>(); /* non-static */ { errorStatuses.add(HttpStatus.BAD_REQUEST); errorStatuses.add(HttpStatus.UNAUTHORIZED); errorStatuses.add(HttpStatus.FORBIDDEN); errorStatuses.add(HttpStatus.NOT_FOUND); errorStatuses.add(HttpStatus.METHOD_NOT_ALLOWED); errorStatuses.add(HttpStatus.NOT_ACCEPTABLE); errorStatuses.add(HttpStatus.REQUEST_TIMEOUT); errorStatuses.add(HttpStatus.CONFLICT); errorStatuses.add(HttpStatus.REQUEST_ENTITY_TOO_LARGE); errorStatuses.add(HttpStatus.REQUEST_URI_TOO_LONG); errorStatuses.add(HttpStatus.UNSUPPORTED_MEDIA_TYPE); errorStatuses.add(HttpStatus.TOO_MANY_REQUESTS); errorStatuses.add(HttpStatus.INTERNAL_SERVER_ERROR); errorStatuses.add(HttpStatus.NOT_IMPLEMENTED); errorStatuses.add(HttpStatus.BAD_GATEWAY); errorStatuses.add(HttpStatus.SERVICE_UNAVAILABLE); }/*from w w w .j a va2 s .co m*/ @Override public boolean hasError(final ClientHttpResponse response) throws IOException { return errorStatuses.contains(response.getStatusCode()); } @Override public void handleError(final ClientHttpResponse response) throws IOException { System.err.printf("%1$d - %2$s%n", response.getRawStatusCode(), response.getStatusText()); System.err.println(readBody(response)); } private String readBody(final ClientHttpResponse response) throws IOException { BufferedReader responseBodyReader = null; try { responseBodyReader = new BufferedReader(new InputStreamReader(response.getBody())); StringBuilder buffer = new StringBuilder(); String line; while ((line = responseBodyReader.readLine()) != null) { buffer.append(line).append(System.getProperty("line.separator")); } return buffer.toString().trim(); } finally { FileSystemUtils.close(responseBodyReader); } } }); return restTemplate; }
From source file:org.openflamingo.uploader.handler.HttpToLocalHandler.java
/** * HTTP URL? ./*from www .j a v a 2s .co m*/ * * @param http HTTP * @return HTTP Response String * @throws Exception HTTP ? ?? ? ? */ private String getResponse(Http http) throws Exception { jobLogger.info("HTTP URL? ? ."); String url = jobContext.getValue(http.getUrl()); String method = jobContext.getValue(http.getMethod().getType()); String body = jobContext.getValue(http.getBody()); jobLogger.info("HTTP URL Information :"); jobLogger.info("\tURL = {}", url); jobLogger.info("\tMethod = {}", method); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); ClientHttpRequest request = null; if ("POST".equals(method)) { request = factory.createRequest(new java.net.URI(url), POST); } else { request = factory.createRequest(new java.net.URI(url), GET); } if (http.getHeaders() != null && http.getHeaders().getHeader().size() > 0) { List<Header> header = http.getHeaders().getHeader(); jobLogger.info("HTTP Header :", new String[] {}); for (Header h : header) { String name = h.getName(); String value = jobContext.getValue(h.getValue()); request.getHeaders().add(name, value); jobLogger.info("\t{} = {}", name, value); } } String responseBodyAsString = null; ClientHttpResponse response = null; try { response = request.execute(); responseBodyAsString = new String(FileCopyUtils.copyToByteArray(response.getBody()), Charset.defaultCharset()); jobLogger.debug("HTTP ? ? ? .\n{}", responseBodyAsString); jobLogger.info("HTTP ? . ? '{}({})'.", response.getStatusText(), response.getRawStatusCode()); if (response.getRawStatusCode() != HttpStatus.ORDINAL_200_OK) { throw new SystemException(ExceptionUtils.getMessage( "HTTP URL ? . ? OK '{}({})' ? .", response.getStatusText(), response.getRawStatusCode())); } } catch (Exception ex) { ex.printStackTrace(); throw new SystemException( ExceptionUtils.getMessage("HTTP URL ? . ? : {}", ExceptionUtils.getRootCause(ex).getMessage()), ex); } finally { try { response.close(); } catch (Exception ex) { // Ignored } } return responseBodyAsString; }
From source file:org.fao.geonet.api.mapservers.GeoServerRest.java
/** * @param method e.g. 'POST', 'GET', 'PUT' or 'DELETE' * @param urlParams REST API parameter * @param postData XML data/*from ww w. j ava 2s . com*/ * @param file File to upload * @param contentType type of content in case of post data or file updload. */ public @CheckReturnValue int sendREST(String method, String urlParams, String postData, Path file, String contentType, Boolean saveResponse) throws IOException { response = ""; String url = this.restUrl + urlParams; if (Log.isDebugEnabled(LOGGER_NAME)) { Log.debug(LOGGER_NAME, "url:" + url); Log.debug(LOGGER_NAME, "method:" + method); if (postData != null) Log.debug(LOGGER_NAME, "postData:" + postData); } HttpRequestBase m; if (method.equals(METHOD_PUT)) { m = new HttpPut(url); if (file != null) { ((HttpPut) m) .setEntity(new PathHttpEntity(file, ContentType.create(contentType, Constants.ENCODING))); } if (postData != null) { final StringEntity entity = new StringEntity(postData, ContentType.create(contentType, Constants.ENCODING)); ((HttpPut) m).setEntity(entity); } } else if (method.equals(METHOD_DELETE)) { m = new HttpDelete(url); } else if (method.equals(METHOD_POST)) { m = new HttpPost(url); if (postData != null) { final StringEntity entity = new StringEntity(postData, ContentType.create(contentType, Constants.ENCODING)); ((HttpPost) m).setEntity(entity); } } else { m = new HttpGet(url); } if (contentType != null && !"".equals(contentType)) { m.setHeader("Content-type", contentType); } m.setConfig(RequestConfig.custom().setAuthenticationEnabled(true).build()); // apparently this is needed to preemptively send the auth, for servers that dont require it but // dont send the same data if you're authenticated or not. try { m.addHeader(new BasicScheme().authenticate(new UsernamePasswordCredentials(username, password), m)); } catch (AuthenticationException a) { Log.warning(LOGGER_NAME, "Failed to add the authentication Header, error is: " + a.getMessage()); } ; final ClientHttpResponse httpResponse = factory.execute(m, new UsernamePasswordCredentials(username, password), AuthScope.ANY); try { status = httpResponse.getRawStatusCode(); if (Log.isDebugEnabled(LOGGER_NAME)) { Log.debug(LOGGER_NAME, "status:" + status); } if (saveResponse) { this.response = IOUtils.toString(httpResponse.getBody()); } } finally { httpResponse.close(); } return status; }
From source file:com.tyro.oss.pact.spring4.pact.consumer.ReturnExpect.java
private void getOrCreateWorkflowAndAddInteraction(Pact pact, ClientHttpRequest clientRequest, ClientHttpResponse response) throws IOException { String bodyString = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()); response.getBody().reset();//from w w w. j ava 2s. com Pact.Interaction interaction = new Pact.Interaction(null, new Pact.InteractionRequest(restRequestDescriptor.getMethod(), urlencode(restRequestDescriptor.getUrl()), clientRequest.getHeaders(), extractBodyContent(restRequestDescriptor.getRequest())), new Pact.InteractionResponse(response.getRawStatusCode(), response.getHeaders(), bodyString, schema), objectConverter); Pact.Workflow workflow = pact.getWorkflow(this.workflowId, this.providerStates); workflow.addInteraction(interaction); }
From source file:org.fao.geonet.api.records.formatters.FormatterApi.java
private String getXmlFromUrl(ServiceContext context, String lang, String url, WebRequest request) throws IOException, URISyntaxException { String adjustedUrl = url;//from w w w . j a va 2 s .c om if (!url.startsWith("http")) { adjustedUrl = context.getBean(SettingManager.class).getSiteURL(lang) + url; } else { final URI uri = new URI(url); Set allowedRemoteHosts = context.getApplicationContext().getBean("formatterRemoteFormatAllowedHosts", Set.class); Assert.isTrue(allowedRemoteHosts.contains(uri.getHost()), "xml.format is not allowed to make requests to " + uri.getHost()); } HttpUriRequest getXmlRequest = new HttpGet(adjustedUrl); final Iterator<String> headerNames = request.getHeaderNames(); while (headerNames.hasNext()) { String headerName = headerNames.next(); final String[] headers = request.getHeaderValues(headerName); for (String header : headers) { getXmlRequest.addHeader(headerName, header); } } GeonetHttpRequestFactory requestFactory = context.getBean(GeonetHttpRequestFactory.class); final ClientHttpResponse execute = requestFactory.execute(getXmlRequest); if (execute.getRawStatusCode() != 200) { throw new IllegalArgumentException("Request " + adjustedUrl + " did not succeed. Response Status: " + execute.getStatusCode() + ", status text: " + execute.getStatusText()); } return new String(ByteStreams.toByteArray(execute.getBody()), Constants.CHARSET); }
From source file:com.kixeye.chassis.transport.HttpTransportTest.java
@Test public void testHttpServiceWithXml() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); properties.put("websocket.enabled", "false"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(TestRestService.class); try {//from w w w. j a v a2s . c o m context.refresh(); final MessageSerDe serDe = context.getBean(XmlMessageSerDe.class); RestTemplate httpClient = new RestTemplate(new HttpComponentsClientHttpRequestFactory()); httpClient.setErrorHandler(new ResponseErrorHandler() { public boolean hasError(ClientHttpResponse response) throws IOException { return response.getRawStatusCode() == HttpStatus.OK.value(); } public void handleError(ClientHttpResponse response) throws IOException { } }); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>( Lists.newArrayList(new SerDeHttpMessageConverter(serDe)))); TestObject response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.postForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject("more stuff"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); ResponseEntity<ServiceError> error = httpClient.postForEntity( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code); error = httpClient.getForEntity( new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode()); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description); error = httpClient.getForEntity( new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code); } finally { context.close(); } }
From source file:com.kixeye.chassis.transport.HttpTransportTest.java
@Test public void testHttpServiceWithYaml() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); properties.put("websocket.enabled", "false"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(TestRestService.class); try {//from w w w . ja va 2s . com context.refresh(); final MessageSerDe serDe = context.getBean(YamlJacksonMessageSerDe.class); RestTemplate httpClient = new RestTemplate(new HttpComponentsClientHttpRequestFactory()); httpClient.setErrorHandler(new ResponseErrorHandler() { public boolean hasError(ClientHttpResponse response) throws IOException { return response.getRawStatusCode() == HttpStatus.OK.value(); } public void handleError(ClientHttpResponse response) throws IOException { } }); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>( Lists.newArrayList(new SerDeHttpMessageConverter(serDe)))); TestObject response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.postForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject("more stuff"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); ResponseEntity<ServiceError> error = httpClient.postForEntity( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code); error = httpClient.getForEntity( new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode()); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description); error = httpClient.getForEntity( new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code); } finally { context.close(); } }