Java Code Examples for org.springframework.web.client.HttpStatusCodeException#getStatusCode()

The following examples show how to use org.springframework.web.client.HttpStatusCodeException#getStatusCode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RestClient.java    From hygieia-core with Apache License 2.0 6 votes vote down vote up
/**
 * The most general version of POST call
 * @param url
 * @param httpEntity HTTP headers and body
 * @return
 */
private <T> ResponseEntity<String> makeRestCallPost(String url, HttpEntity<T> httpEntity) {

    long start = System.currentTimeMillis();
    ResponseEntity<String> response;
    HttpStatus status = null;
    try {
        response = restOperations.exchange(url, HttpMethod.POST, httpEntity, String.class);
        status = response.getStatusCode();
    } catch (HttpStatusCodeException e) {
        status = e.getStatusCode();
        LOG.info("status=" + status + ", requestBody=" + httpEntity.getBody());
        throw e;
    } finally {
        long end = System.currentTimeMillis();
        LOG.info("makeRestCall op=POST url=" + url + ", status=" + status + " duration=" + (end - start));
    }

    return response;
}
 
Example 2
Source File: RestClient.java    From hygieia-core with Apache License 2.0 6 votes vote down vote up
/**
 * The most general form of GET calls.
 * @param url
 * @param headers Can be null if no header is needed
 * @return
 * @throws RestClientException
 */
public ResponseEntity<String> makeRestCallGet(String url, HttpHeaders headers) throws RestClientException {

    long start = System.currentTimeMillis();
    ResponseEntity<String> response;
    HttpStatus status = null;
    try {
        HttpEntity entity = headers==null?null:new HttpEntity(headers);
        response = restOperations.exchange(url, HttpMethod.GET, entity, String.class);
        status = response.getStatusCode();
    } catch (HttpStatusCodeException e) {
        status = e.getStatusCode();
        throw e;
    } finally {
        long end = System.currentTimeMillis();
        LOG.info("makeRestCall op=GET url=" + url + " status=" + status + " duration=" + (end - start));
    }
    return response;
}
 
Example 3
Source File: AbstractServiceApiPlusListener.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * 调用下游服务
 *
 * @param context
 * @return
 */
public ResponseEntity<String> callOrderService(DataFlowContext context, JSONObject paramIn) {

    context.getRequestCurrentHeaders().put(CommonConstant.HTTP_ORDER_TYPE_CD, "D");
    ResponseEntity responseEntity = null;
    if (paramIn == null || paramIn.isEmpty()) {
        paramIn = context.getReqJson();
    }
    String serviceUrl = ORDER_SERVICE_URL;
    HttpEntity<String> httpEntity = null;
    HttpHeaders header = new HttpHeaders();
    for (String key : context.getRequestCurrentHeaders().keySet()) {
        if (CommonConstant.HTTP_SERVICE.toLowerCase().equals(key.toLowerCase())) {
            continue;
        }
        header.add(key, context.getRequestCurrentHeaders().get(key));
    }
    try {
        httpEntity = new HttpEntity<String>(JSONObject.toJSONString(paramIn), header);
        responseEntity = restTemplate.exchange(serviceUrl, HttpMethod.POST, httpEntity, String.class);
    } catch (HttpStatusCodeException e) { //这里spring 框架 在4XX 或 5XX 时抛出 HttpServerErrorException 异常,需要重新封装一下
        responseEntity = new ResponseEntity<String>(e.getResponseBodyAsString(), e.getStatusCode());
    }
    return responseEntity;
}
 
Example 4
Source File: ManifestCommands.java    From spring-cloud-skipper with Apache License 2.0 6 votes vote down vote up
@ShellMethod(key = "manifest get", value = "Get the manifest for a release")
public Object getManifest(
		@ShellOption(help = "release name") @NotNull String releaseName,
		@ShellOption(help = "specific release version.", defaultValue = ShellOption.NULL) Integer releaseVersion) {
	String manifest;
	try {
		if (releaseVersion == null) {
			manifest = this.skipperClient.manifest(releaseName);
		}
		else {
			manifest = this.skipperClient.manifest(releaseName, releaseVersion);
		}
	}
	catch (HttpStatusCodeException e) {
		if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
			return "Release with name '" + releaseName + "' not found";
		}
		// if something else, rethrow
		throw e;
	}
	return manifest;
}
 
Example 5
Source File: AbstractTwitterInboundChannelAdapter.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
	while (running.get()) {
		try {
			readStream(twitter.getRestTemplate());
		}
		catch (HttpStatusCodeException sce) {
			if (sce.getStatusCode() == HttpStatus.UNAUTHORIZED) {
				logger.error("Twitter authentication failed: " + sce.getMessage());
				running.set(false);
			}
			else if (sce.getStatusCode() == HttpStatus.TOO_MANY_REQUESTS) {
				waitRateLimitBackoff();
			}
			else {
				waitHttpErrorBackoff();
			}
		}
		catch (Exception e) {
			logger.warn("Exception while reading stream.", e);
			waitLinearBackoff();
		}
	}
}
 
Example 6
Source File: HealthApi.java    From edison-microservice with Apache License 2.0 6 votes vote down vote up
private static void getResource(final String url, final Optional<String> mediaType) {
    final HttpHeaders headers = new HttpHeaders();
    if (mediaType.isPresent()) {
        headers.setAccept(asList(parseMediaType(mediaType.get())));
    }
    try {
        final ResponseEntity<String> responseEntity = restTemplate.exchange(
                url,
                GET,
                new HttpEntity<>("parameters", headers), String.class
        );
        content = responseEntity.getBody();
        statusCode = responseEntity.getStatusCode();
    } catch (HttpStatusCodeException e) {
        content = e.getStatusText();
        statusCode = e.getStatusCode();
    }
}
 
Example 7
Source File: StandardBullhornData.java    From sdk-rest with MIT License 6 votes vote down vote up
/**
 * @param uriVariables
 * @param tryNumber
 * @param error
 * @throws RestApiException if tryNumber >= API_RETRY.
 */
protected boolean handleHttpStatusCodeError(Map<String, String> uriVariables, int tryNumber, HttpStatusCodeException error) {
    boolean isTooManyRequestsError = false;
    if (error.getStatusCode() == HttpStatus.UNAUTHORIZED) {
        resetBhRestToken(uriVariables);
    } else if (error.getStatusCode() == HttpStatus.TOO_MANY_REQUESTS) {
        isTooManyRequestsError = true;
    }
    log.error(
            "HttpStatusCodeError making api call. Try number:" + tryNumber + " out of " + API_RETRY + ". Http status code: "
                    + error.getStatusCode() + ". Response body: " + error.getResponseBodyAsString(), error);
    if (tryNumber >= API_RETRY && !isTooManyRequestsError) {
        throw new RestApiException("HttpStatusCodeError making api call with url variables " + uriVariables.toString()
                + ". Http status code: " + error.getStatusCode().toString() + ". Response body: " + error == null ? ""
                : error.getResponseBodyAsString());
    }
    return isTooManyRequestsError;
}
 
Example 8
Source File: VaultKvAccessStrategySupport.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
/**
 * @param headers must not be {@literal null}.
 * @param backend secret backend mount path, must not be {@literal null}.
 * @param key key within the key-value secret backend, must not be {@literal null}.
 * @return
 */
@Override
public String getData(HttpHeaders headers, String backend, String key) {
	try {

		String urlTemplate = String.format("%s/v1/%s/%s", this.baseUrl, backend,
				getPath());

		ResponseEntity<VaultResponse> response = this.rest.exchange(urlTemplate,
				HttpMethod.GET, new HttpEntity<>(headers), VaultResponse.class, key);
		HttpStatus status = response.getStatusCode();
		if (status == HttpStatus.OK) {
			return extractDataFromBody(response.getBody());
		}
	}
	catch (HttpStatusCodeException e) {
		if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
			return null;
		}
		throw e;
	}
	return null;
}
 
Example 9
Source File: RestTemplateHttpClient.java    From trello-java-wrapper with Apache License 2.0 5 votes vote down vote up
private static RuntimeException translateException(HttpStatusCodeException e) {
    String response = e.getResponseBodyAsString();

    switch (e.getStatusCode()) {
        case BAD_REQUEST:
            return new TrelloBadRequestException(response, e);
        case NOT_FOUND:
            return new NotFoundException(response, e);
        case UNAUTHORIZED:
            return new NotAuthorizedException(response, e);
        default:
            return new TrelloHttpException(e);
    }
}
 
Example 10
Source File: CustomControllerClientErrorHandler.java    From multiapps-controller with Apache License 2.0 4 votes vote down vote up
private CloudOperationException asCloudOperationException(HttpStatusCodeException exception) {
    String description = getDescriptionFromResponseBody(exception.getResponseBodyAsString());
    return new CloudOperationException(exception.getStatusCode(), exception.getStatusText(), description);
}
 
Example 11
Source File: CredHubException.java    From spring-credhub with Apache License 2.0 2 votes vote down vote up
/**
 * Create a new exception with the provided root cause.
 * @param e an {@link HttpStatusCodeException} caught while attempting to communicate
 * with CredHub
 */
public CredHubException(HttpStatusCodeException e) {
	super(e.getStatusCode(), e.getStatusText(), e.getResponseHeaders(), e.getResponseBodyAsByteArray(), null);
}