List of usage examples for org.springframework.http.client ClientHttpResponse getStatusText
String getStatusText() throws IOException;
From source file:com.art4ul.jcoonsample.client.service.TestService.java
public void doTest() { restClient.setBaseUrl("http://localhost:8080"); LOG.info("Example #1: Send GET request"); ResultModel result = restClient.exampleGetRequest("world"); LOG.info("simpleGetRequestTest return: {} \n", result.getResult()); LOG.info("Example #2: Send POST request with custom base URL"); UserModel userModel = new UserModel("Tester", "sam", "123456"); result = restClient.examplePostRequest("http://localhost:8080", userModel); LOG.info("simpleGetRequestTest return: {} \n", result.getResult()); LOG.info("Example #3: Send POST request with custom HTTP header"); result = restClient.examplePostRequestWithHeader(userModel, "test value"); LOG.info("simpleGetRequestTest return: {} \n", result.getResult()); LOG.info("Example #4: Send Get request with path variable"); result = restClient.exampleGetRequestWithPathVariable("test"); LOG.info("simpleGetRequestTest return: {} \n", result.getResult()); LOG.info("Example #5: Handle HTTP exception"); ResponseErrorHandler responseErrorHandler = new ResponseErrorHandler() { @Override/* w w w .j ava 2 s .c om*/ public boolean hasError(ClientHttpResponse response) throws IOException { return true; } @Override public void handleError(ClientHttpResponse response) throws IOException { throw new CustomException( "HTTP code: " + response.getStatusCode() + " text: " + response.getStatusText()); } }; try { result = restClient.exampleException("test", responseErrorHandler); } catch (CustomException ex) { LOG.info("Exception: " + ex.getMessage()); } }
From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.ApiResponseErrorHandler.java
/** * {@inheritDoc}/*from w w w . j a v a 2 s . c o m*/ * <p> * This implementation handles the HTTP error response by throwing an {@link ApiErrorResponseException} which includes * an {@link ApiError error} if the response body contained an API error entity. */ @Override public void handleError(ClientHttpResponse response) throws ApiErrorResponseException, IOException { HttpStatus statusCode = getHttpStatusCode(response); ApiError apiError = this.extractErrorResponse(response); throw new ApiErrorResponseException(statusCode.value(), response.getStatusText(), response.getHeaders(), getCharset(response), getResponseBody(response), apiError); }
From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.ApiResponseErrorHandler.java
private HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException { HttpStatus statusCode;//w w w. j a v a 2 s. c o m try { statusCode = response.getStatusCode(); } catch (IllegalArgumentException ex) { throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response)); } return statusCode; }
From source file:com.sastix.cms.common.client.exception.CommonExceptionHandler.java
/** * This default implementation throws a {@link HttpClientErrorException} if the response status code * is {@link HttpStatus.Series#CLIENT_ERROR}, a {@link HttpServerErrorException} * if it is {@link HttpStatus.Series#SERVER_ERROR}, * and a {@link RestClientException} in other cases. *///from w w w.ja va 2s. co m @Override public void handleError(ClientHttpResponse response) throws IOException, RestClientException { HttpStatus statusCode = getHttpStatusCode(response); switch (statusCode.series()) { case CLIENT_ERROR: final byte[] responseBody = getResponseBody(response); final Charset charset = getCharset(response); final String statusText = response.getStatusText(); final HttpHeaders httpHeaders = response.getHeaders(); final RestErrorDTO errorDTO; try { errorDTO = objectMapper.readValue(new String(responseBody, charset), RestErrorDTO.class); LOG.error("Exception: " + errorDTO.toString()); } catch (final Exception e) { //Wasn't able to map String on ErrorDTO. //It is an Unknown Exception //Throw Default Exception final HttpClientErrorException clientErrorException = new HttpClientErrorException(statusCode, statusText, httpHeaders, responseBody, charset); LOG.error("Unknown Exception: " + clientErrorException.getMessage()); throw clientErrorException; } if (exceptionClasses.containsKey(errorDTO.getException())) { throw (exceptionClasses.get(errorDTO.getException())).create(errorDTO.getMessage()); } else { throw new HttpClientErrorException(statusCode, statusText, httpHeaders, responseBody, charset); } case SERVER_ERROR: throw new HttpServerErrorException(statusCode, response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response)); default: throw new RestClientException("Unknown status code [" + statusCode + "]"); } }
From source file:org.intermine.app.net.ServerErrorHandler.java
@Override public void handleError(ClientHttpResponse response) throws IOException { InputStream inputStream = response.getBody(); String body = Strs.nullToEmpty(IOUtils.toString(inputStream, DEFAULT_ENCODING)); String errorMessage = null;//from ww w .jav a 2 s. c om try { Map<String, String> map = mMapper.fromJson(body, Map.class); if (null != map) { errorMessage = map.get(ERROR_KEY); } } catch (JsonSyntaxException ex) { } HttpNetworkException e = new HttpNetworkException(response.getStatusText()); e.setErrorMessage(Strs.isNullOrEmpty(errorMessage) ? body : errorMessage); e.setHeaders(response.getHeaders()); e.setStatusCode(response.getStatusCode()); throw e; }
From source file:com.cisco.cta.taxii.adapter.ResponseTransformer.java
/** * Transforms TAXII response.// w w w . ja v a 2 s . c o m * * @param resp HTTP response * @return TaxiiPollResponse if valid TAXII poll response was returned * @throws Exception When any error occurs. */ public TaxiiPollResponse transform(ClientHttpResponse resp) throws Exception { if (resp.getRawStatusCode() == HTTP_OK) { try (InputStream body = resp.getBody()) { TaxiiPollResponseReader responseReader = readerFactory.create(body); Transformer transformer = templates.newTransformer(); transformer.transform(new StAXSource(responseReader), new StreamResult(logWriter)); return responseReader.getResponse(); } } else { throw new IOException("HTTP response status " + resp.getRawStatusCode() + ":" + resp.getStatusText()); } }
From source file:com.evolveum.midpoint.notifications.impl.api.transports.SimpleSmsTransport.java
@Override public void send(Message message, String transportName, Event event, Task task, OperationResult parentResult) { OperationResult result = parentResult.createSubresult(DOT_CLASS + "send"); result.addArbitraryObjectCollectionAsParam("message recipient(s)", message.getTo()); result.addParam("message subject", message.getSubject()); SystemConfigurationType systemConfiguration = NotificationFunctionsImpl .getSystemConfiguration(cacheRepositoryService, result); if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null) { String msg = "No notifications are configured. SMS notification to " + message.getTo() + " will not be sent."; LOGGER.warn(msg);/*from w ww .j ava 2 s .c o m*/ result.recordWarning(msg); return; } String smsConfigName = StringUtils.substringAfter(transportName, NAME + ":"); SmsConfigurationType found = null; for (SmsConfigurationType smsConfigurationType : systemConfiguration.getNotificationConfiguration() .getSms()) { if (StringUtils.isEmpty(smsConfigName) && smsConfigurationType.getName() == null || StringUtils.isNotEmpty(smsConfigName) && smsConfigName.equals(smsConfigurationType.getName())) { found = smsConfigurationType; break; } } if (found == null) { String msg = "SMS configuration '" + smsConfigName + "' not found. SMS notification to " + message.getTo() + " will not be sent."; LOGGER.warn(msg); result.recordWarning(msg); return; } SmsConfigurationType smsConfigurationType = found; String logToFile = smsConfigurationType.getLogToFile(); if (logToFile != null) { TransportUtil.logToFile(logToFile, TransportUtil.formatToFileNew(message, transportName), LOGGER); } String file = smsConfigurationType.getRedirectToFile(); if (file != null) { writeToFile(message, file, null, emptyList(), null, result); return; } if (smsConfigurationType.getGateway().isEmpty()) { String msg = "SMS gateway(s) are not defined, notification to " + message.getTo() + " will not be sent."; LOGGER.warn(msg); result.recordWarning(msg); return; } String from; if (message.getFrom() != null) { from = message.getFrom(); } else if (smsConfigurationType.getDefaultFrom() != null) { from = smsConfigurationType.getDefaultFrom(); } else { from = ""; } if (message.getTo().isEmpty()) { String msg = "There is no recipient to send the notification to."; LOGGER.warn(msg); result.recordWarning(msg); return; } List<String> to = message.getTo(); assert to.size() > 0; for (SmsGatewayConfigurationType smsGatewayConfigurationType : smsConfigurationType.getGateway()) { OperationResult resultForGateway = result.createSubresult(DOT_CLASS + "send.forGateway"); resultForGateway.addContext("gateway name", smsGatewayConfigurationType.getName()); try { ExpressionVariables variables = getDefaultVariables(from, to, message); HttpMethodType method = defaultIfNull(smsGatewayConfigurationType.getMethod(), HttpMethodType.GET); ExpressionType urlExpression = defaultIfNull(smsGatewayConfigurationType.getUrlExpression(), smsGatewayConfigurationType.getUrl()); String url = evaluateExpressionChecked(urlExpression, variables, "sms gateway request url", task, result); LOGGER.debug("Sending SMS to URL {} (method {})", url, method); if (url == null) { throw new IllegalArgumentException("No URL specified"); } List<String> headersList = evaluateExpressionsChecked( smsGatewayConfigurationType.getHeadersExpression(), variables, "sms gateway request headers", task, result); LOGGER.debug("Using request headers:\n{}", headersList); String encoding = defaultIfNull(smsGatewayConfigurationType.getBodyEncoding(), StandardCharsets.ISO_8859_1.name()); String body = evaluateExpressionChecked(smsGatewayConfigurationType.getBodyExpression(), variables, "sms gateway request body", task, result); LOGGER.debug("Using request body text (encoding: {}):\n{}", encoding, body); if (smsGatewayConfigurationType.getLogToFile() != null) { TransportUtil.logToFile(smsGatewayConfigurationType.getLogToFile(), formatToFile(message, url, headersList, body), LOGGER); } if (smsGatewayConfigurationType.getRedirectToFile() != null) { writeToFile(message, smsGatewayConfigurationType.getRedirectToFile(), url, headersList, body, resultForGateway); result.computeStatus(); return; } else { HttpClientBuilder builder = HttpClientBuilder.create(); String username = smsGatewayConfigurationType.getUsername(); ProtectedStringType password = smsGatewayConfigurationType.getPassword(); if (username != null) { CredentialsProvider provider = new BasicCredentialsProvider(); String plainPassword = password != null ? protector.decryptString(password) : null; UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, plainPassword); provider.setCredentials(AuthScope.ANY, credentials); builder = builder.setDefaultCredentialsProvider(provider); } HttpClient client = builder.build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( client); ClientHttpRequest request = requestFactory.createRequest(new URI(url), HttpUtil.toHttpMethod(method)); setHeaders(request, headersList); if (body != null) { request.getBody().write(body.getBytes(encoding)); } ClientHttpResponse response = request.execute(); LOGGER.debug("Result: " + response.getStatusCode() + "/" + response.getStatusText()); if (response.getStatusCode().series() != HttpStatus.Series.SUCCESSFUL) { throw new SystemException("SMS gateway communication failed: " + response.getStatusCode() + ": " + response.getStatusText()); } LOGGER.info("Message sent successfully to {} via gateway {}.", message.getTo(), smsGatewayConfigurationType.getName()); resultForGateway.recordSuccess(); result.recordSuccess(); return; } } catch (Throwable t) { String msg = "Couldn't send SMS to " + message.getTo() + " via " + smsGatewayConfigurationType.getName() + ", trying another gateway, if there is any"; LoggingUtils.logException(LOGGER, msg, t); resultForGateway.recordFatalError(msg, t); } } LOGGER.warn("No more SMS gateways to try, notification to " + message.getTo() + " will not be sent."); result.recordWarning("Notification to " + message.getTo() + " could not be sent."); }
From source file:com.pepaproch.gtswsdl.LoginRequestInterceptor.java
private ClientHttpResponse logResponse(ClientHttpResponse response) throws IOException { ClientHttpResponse result = new ClientHttpResponse() { InputStream in;//from w w w . j a v a2 s. c o m InputStream oldIn = response.getBody(); String jsonResponse; @Override public HttpStatus getStatusCode() throws IOException { return response.getStatusCode(); } @Override public int getRawStatusCode() throws IOException { return response.getRawStatusCode(); } @Override public String getStatusText() throws IOException { return response.getStatusText(); } @Override public void close() { try { Logger.getLogger(LoginRequestInterceptor.class).log(Level.DEBUG, jsonResponse); in.close(); oldIn.close(); } catch (IOException ex) { java.util.logging.Logger.getLogger(LoginRequestInterceptor.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } } @Override public InputStream getBody() throws IOException { if (in == null) { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { byte[] readBuffer = new byte[4 * 1024]; int lenght; while ((lenght = oldIn.read(readBuffer)) != -1) { baos.write(readBuffer, 0, lenght); } baos.flush(); jsonResponse = baos.toString(); in = new ByteArrayInputStream(baos.toByteArray()); } } return in; } @Override public HttpHeaders getHeaders() { return response.getHeaders(); } }; return result; }
From source file:org.openflamingo.uploader.handler.HttpToLocalHandler.java
/** * HTTP URL? .//from w w w .j a va2s . com * * @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.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); }/*ww w. ja va 2s .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; }