org.springframework.http.HttpStatus#resolve ( )源码实例Demo

下面列出了org.springframework.http.HttpStatus#resolve ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: spring-analysis-note   文件: DefaultWebClient.java
private <T extends Publisher<?>> T handleBody(ClientResponse response,
		T bodyPublisher, Function<Mono<? extends Throwable>, T> errorFunction) {

	if (HttpStatus.resolve(response.rawStatusCode()) != null) {
		for (StatusHandler handler : this.statusHandlers) {
			if (handler.test(response.statusCode())) {
				HttpRequest request = this.requestSupplier.get();
				Mono<? extends Throwable> exMono = handler.apply(response, request);
				exMono = exMono.flatMap(ex -> drainBody(response, ex));
				exMono = exMono.onErrorResume(ex -> drainBody(response, ex));
				T result = errorFunction.apply(exMono);
				return insertCheckpoint(result, response.statusCode(), request);
			}
		}
		return bodyPublisher;
	}
	else {
		return errorFunction.apply(createResponseException(response, this.requestSupplier.get()));
	}
}
 
源代码2 项目: spring-cloud-gateway   文件: NettyRoutingFilter.java
private void setResponseStatus(HttpClientResponse clientResponse,
		ServerHttpResponse response) {
	HttpStatus status = HttpStatus.resolve(clientResponse.status().code());
	if (status != null) {
		response.setStatusCode(status);
	}
	else {
		while (response instanceof ServerHttpResponseDecorator) {
			response = ((ServerHttpResponseDecorator) response).getDelegate();
		}
		if (response instanceof AbstractServerHttpResponse) {
			((AbstractServerHttpResponse) response)
					.setStatusCodeValue(clientResponse.status().code());
		}
		else {
			// TODO: log warning here, not throw error?
			throw new IllegalStateException("Unable to set status code "
					+ clientResponse.status().code() + " on response of type "
					+ response.getClass().getName());
		}
	}
}
 
@GetMapping(path = RESPONSE_STATUS_EX_FOR_SPECIFIC_STATUS_CODE_ENDPOINT)
@ResponseBody
public String responseStatusExForSpecificStatusCodeEndpoint(ServerHttpRequest request) {
    int desiredStatusCode = Integer.parseInt(
        request.getHeaders().getFirst("desired-status-code")
    );
    throw new ResponseStatusException(
        HttpStatus.resolve(desiredStatusCode),
        "Synthetic ResponseStatusException with specific desired status code: " + desiredStatusCode
    );
}
 
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
    Object handler, Exception ex) {
  if (!(HttpMethod.GET.matches(request.getMethod())
      || HttpMethod.DELETE.matches(request.getMethod()))) {
    String path = request.getRequestURI();
    HttpStatus status = HttpStatus.resolve(response.getStatus());
    if (!path.contains(ResourcePath.OPEN) && status != null && !status.isError()) {
      logHelper.log(HttpMethod.resolve(request.getMethod()), path);
    }
  }
}
 
private void writeStatusAndHeaders(ServerHttpResponse response) {
	if (response instanceof AbstractServerHttpResponse) {
		((AbstractServerHttpResponse) response).setStatusCodeValue(this.statusCode);
	}
	else {
		HttpStatus status = HttpStatus.resolve(this.statusCode);
		if (status == null) {
			throw new IllegalStateException(
					"Unresolvable HttpStatus for general ServerHttpResponse: " + this.statusCode);
		}
		response.setStatusCode(status);
	}
	copy(this.headers, response.getHeaders());
	copy(this.cookies, response.getCookies());
}
 
private void writeStatusAndHeaders(ServerHttpResponse response) {
	if (response instanceof AbstractServerHttpResponse) {
		((AbstractServerHttpResponse) response).setStatusCodeValue(this.statusCode);
	}
	else {
		HttpStatus status = HttpStatus.resolve(this.statusCode);
		if (status == null) {
			throw new IllegalStateException(
					"Unresolvable HttpStatus for general ServerHttpResponse: " + this.statusCode);
		}
		response.setStatusCode(status);
	}
	copy(this.headers, response.getHeaders());
	copy(this.cookies, response.getCookies());
}
 
/**
 * Delegates to {@link #handleError(ClientHttpResponse, HttpStatus)} with the
 * response status code.
 * @throws UnknownHttpStatusCodeException in case of an unresolvable status code
 * @see #handleError(ClientHttpResponse, HttpStatus)
 */
@Override
public void handleError(ClientHttpResponse response) throws IOException {
	HttpStatus statusCode = HttpStatus.resolve(response.getRawStatusCode());
	if (statusCode == null) {
		throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(),
				response.getHeaders(), getResponseBody(response), getCharset(response));
	}
	handleError(response, statusCode);
}
 
源代码8 项目: kayenta   文件: SynchronousQueryProcessor.java
private boolean isRetryable(RetrofitError e) {
  if (isNetworkError(e)) {
    // retry in case of network errors
    return true;
  }
  HttpStatus responseStatus = HttpStatus.resolve(e.getResponse().getStatus());
  if (responseStatus == null) {
    return false;
  }
  return retryConfiguration.getStatuses().contains(responseStatus)
      || retryConfiguration.getSeries().contains(responseStatus.series());
}
 
源代码9 项目: mPaaS   文件: RestResponseErrorHandler.java
@Override
public void handleError(ClientHttpResponse response) throws IOException {
    HttpStatus statusCode = HttpStatus.resolve(response.getRawStatusCode());
    if (statusCode == null) {
        throw new KmssServiceException("errors.unkown", new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(),response.getHeaders(), getResponseBody(response), getCharset(response)));
    }
    handleError(response, statusCode);
}
 
/**
 * Indicates whether the response has a message body.
 * <p>Implementation returns {@code false} for:
 * <ul>
 * <li>a response status of {@code 1XX}, {@code 204} or {@code 304}</li>
 * <li>a {@code Content-Length} header of {@code 0}</li>
 * </ul>
 * @return {@code true} if the response has a message body, {@code false} otherwise
 * @throws IOException in case of I/O errors
 */
public boolean hasMessageBody() throws IOException {
	HttpStatus status = HttpStatus.resolve(getRawStatusCode());
	if (status != null && (status.is1xxInformational() || status == HttpStatus.NO_CONTENT ||
			status == HttpStatus.NOT_MODIFIED)) {
		return false;
	}
	if (getHeaders().getContentLength() == 0) {
		return false;
	}
	return true;
}
 
public static HttpStatus parse(String statusString) {
	HttpStatus httpStatus;

	try {
		int status = Integer.parseInt(statusString);
		httpStatus = HttpStatus.resolve(status);
	}
	catch (NumberFormatException e) {
		// try the enum string
		httpStatus = HttpStatus.valueOf(statusString.toUpperCase());
	}
	return httpStatus;
}
 
/**
 * Create {@code WebClientResponseException} or an HTTP status specific subclass.
 * @since 5.1.4
 */
public static WebClientResponseException create(
		int statusCode, String statusText, HttpHeaders headers, byte[] body,
		@Nullable Charset charset, @Nullable HttpRequest request) {

	HttpStatus httpStatus = HttpStatus.resolve(statusCode);
	if (httpStatus != null) {
		switch (httpStatus) {
			case BAD_REQUEST:
				return new WebClientResponseException.BadRequest(statusText, headers, body, charset, request);
			case UNAUTHORIZED:
				return new WebClientResponseException.Unauthorized(statusText, headers, body, charset, request);
			case FORBIDDEN:
				return new WebClientResponseException.Forbidden(statusText, headers, body, charset, request);
			case NOT_FOUND:
				return new WebClientResponseException.NotFound(statusText, headers, body, charset, request);
			case METHOD_NOT_ALLOWED:
				return new WebClientResponseException.MethodNotAllowed(statusText, headers, body, charset, request);
			case NOT_ACCEPTABLE:
				return new WebClientResponseException.NotAcceptable(statusText, headers, body, charset, request);
			case CONFLICT:
				return new WebClientResponseException.Conflict(statusText, headers, body, charset, request);
			case GONE:
				return new WebClientResponseException.Gone(statusText, headers, body, charset, request);
			case UNSUPPORTED_MEDIA_TYPE:
				return new WebClientResponseException.UnsupportedMediaType(statusText, headers, body, charset, request);
			case TOO_MANY_REQUESTS:
				return new WebClientResponseException.TooManyRequests(statusText, headers, body, charset, request);
			case UNPROCESSABLE_ENTITY:
				return new WebClientResponseException.UnprocessableEntity(statusText, headers, body, charset, request);
			case INTERNAL_SERVER_ERROR:
				return new WebClientResponseException.InternalServerError(statusText, headers, body, charset, request);
			case NOT_IMPLEMENTED:
				return new WebClientResponseException.NotImplemented(statusText, headers, body, charset, request);
			case BAD_GATEWAY:
				return new WebClientResponseException.BadGateway(statusText, headers, body, charset, request);
			case SERVICE_UNAVAILABLE:
				return new WebClientResponseException.ServiceUnavailable(statusText, headers, body, charset, request);
			case GATEWAY_TIMEOUT:
				return new WebClientResponseException.GatewayTimeout(statusText, headers, body, charset, request);
		}
	}
	return new WebClientResponseException(statusCode, statusText, headers, body, charset, request);
}
 
@Override
public Object extractData(ClientHttpResponse response) throws IOException {
	HttpStatus httpStatus = HttpStatus.resolve(response.getRawStatusCode());
	if (httpStatus == null) {
		throw new UnknownHttpStatusCodeException(
				response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), null, null);
	}
	if (httpStatus != HttpStatus.OK) {
		throw new HttpServerErrorException(
				httpStatus, response.getStatusText(), response.getHeaders(), null, null);
	}

	if (logger.isTraceEnabled()) {
		logger.trace("XHR receive headers: " + response.getHeaders());
	}
	InputStream is = response.getBody();
	ByteArrayOutputStream os = new ByteArrayOutputStream();

	while (true) {
		if (this.sockJsSession.isDisconnected()) {
			if (logger.isDebugEnabled()) {
				logger.debug("SockJS sockJsSession closed, closing response.");
			}
			response.close();
			break;
		}
		int b = is.read();
		if (b == -1) {
			if (os.size() > 0) {
				handleFrame(os);
			}
			if (logger.isTraceEnabled()) {
				logger.trace("XHR receive completed");
			}
			break;
		}
		if (b == '\n') {
			handleFrame(os);
		}
		else {
			os.write(b);
		}
	}
	return null;
}
 
@Override
public Object extractData(ClientHttpResponse response) throws IOException {
	HttpStatus httpStatus = HttpStatus.resolve(response.getRawStatusCode());
	if (httpStatus == null) {
		throw new UnknownHttpStatusCodeException(
				response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), null, null);
	}
	if (httpStatus != HttpStatus.OK) {
		throw new HttpServerErrorException(
				httpStatus, response.getStatusText(), response.getHeaders(), null, null);
	}

	if (logger.isTraceEnabled()) {
		logger.trace("XHR receive headers: " + response.getHeaders());
	}
	InputStream is = response.getBody();
	ByteArrayOutputStream os = new ByteArrayOutputStream();

	while (true) {
		if (this.sockJsSession.isDisconnected()) {
			if (logger.isDebugEnabled()) {
				logger.debug("SockJS sockJsSession closed, closing response.");
			}
			response.close();
			break;
		}
		int b = is.read();
		if (b == -1) {
			if (os.size() > 0) {
				handleFrame(os);
			}
			if (logger.isTraceEnabled()) {
				logger.trace("XHR receive completed");
			}
			break;
		}
		if (b == '\n') {
			handleFrame(os);
		}
		else {
			os.write(b);
		}
	}
	return null;
}
 
private <T> ResponseEntity<T> createEntity(HttpHeaders headers, int status) {
	HttpStatus resolvedStatus = HttpStatus.resolve(status);
	return resolvedStatus != null
			? new ResponseEntity<>(headers, resolvedStatus)
			: ResponseEntity.status(status).headers(headers).build();
}
 
private <T> ResponseEntity<T> createEntity(T body, HttpHeaders headers, int status) {
	HttpStatus resolvedStatus = HttpStatus.resolve(status);
	return resolvedStatus != null
			? new ResponseEntity<>(body, headers, resolvedStatus)
			: ResponseEntity.status(status).headers(headers).body(body);
}
 
@Override
@Nullable
public HttpStatus getStatusCode() {
	return this.statusCode != null ? HttpStatus.resolve(this.statusCode) : null;
}
 
@Override
public HttpStatus getStatusCode() {
	HttpStatus httpStatus = super.getStatusCode();
	return httpStatus != null ? httpStatus : HttpStatus.resolve(this.exchange.getStatusCode());
}
 
@Override
public String getReasonPhrase(int statusCode) {
    HttpStatus status = HttpStatus.resolve(statusCode);
    return status != null ? status.getReasonPhrase() : null;
}
 
/**
 * Determine the HTTP status of the given response.
 * @param response the response to inspect
 * @return the associated HTTP status
 * @throws IOException in case of I/O errors
 * @throws UnknownHttpStatusCodeException in case of an unknown status code
 * that cannot be represented with the {@link HttpStatus} enum
 * @since 4.3.8
 * @deprecated as of 5.0, in favor of {@link #handleError(ClientHttpResponse, HttpStatus)}
 */
@Deprecated
protected HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException {
	HttpStatus statusCode = HttpStatus.resolve(response.getRawStatusCode());
	if (statusCode == null) {
		throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(),
				response.getHeaders(), getResponseBody(response), getCharset(response));
	}
	return statusCode;
}