org.springframework.http.client.ClientHttpResponse#getHeaders ( )源码实例Demo

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

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void handleError(ClientHttpResponse response) throws IOException {
    MediaType mediaType = response.getHeaders().getContentType();
    RestError error = null;
    for(HttpMessageConverter converter : converters) {
        if(converter.canRead(JaxbRestError.class, mediaType)) {
            try {
                error = (RestError)converter.read(JaxbRestError.class, response);
            } catch(Exception e) {
                error = new JaxbRestError();
                ((JaxbRestError)error).setStatus(response.getRawStatusCode());
            }
            break;
        }
    }
    throw new DCTMRestErrorException(response.getHeaders(), response.getStatusCode(), error);
}
 
源代码2 项目: ByteTCC   文件: CompensableRequestInterceptor.java
private void invokeAfterRecvResponse(ClientHttpResponse httpResponse, boolean serverFlag) throws IOException {
	SpringCloudBeanRegistry beanRegistry = SpringCloudBeanRegistry.getInstance();
	CompensableBeanFactory beanFactory = beanRegistry.getBeanFactory();
	TransactionInterceptor transactionInterceptor = beanFactory.getTransactionInterceptor();

	HttpHeaders respHeaders = httpResponse.getHeaders();
	String respTransactionStr = respHeaders.getFirst(HEADER_TRANCACTION_KEY);
	String respPropagationStr = respHeaders.getFirst(HEADER_PROPAGATION_KEY);
	String respRecursivelyStr = respHeaders.getFirst(HEADER_RECURSIVELY_KEY);

	String transactionText = StringUtils.trimToNull(respTransactionStr);
	byte[] byteArray = StringUtils.isBlank(transactionText) ? null : Base64.getDecoder().decode(transactionText);
	TransactionContext serverContext = byteArray == null || byteArray.length == 0 //
			? null
			: (TransactionContext) SerializeUtils.deserializeObject(byteArray);

	TransactionResponseImpl txResp = new TransactionResponseImpl();
	txResp.setTransactionContext(serverContext);
	RemoteCoordinator serverCoordinator = beanRegistry.getConsumeCoordinator(respPropagationStr);
	txResp.setSourceTransactionCoordinator(serverCoordinator);
	txResp.setParticipantDelistFlag(serverFlag ? StringUtils.equalsIgnoreCase(respRecursivelyStr, "TRUE") : true);

	transactionInterceptor.afterReceiveResponse(txResp);
}
 
源代码3 项目: sofa-tracer   文件: RestTemplateInterceptor.java
/**
 * add response tag
 * @param response
 * @param sofaTracerSpan
 */
private void appendRestTemplateResponseSpanTags(ClientHttpResponse response,
                                                SofaTracerSpan sofaTracerSpan) {
    if (sofaTracerSpan == null) {
        return;
    }
    HttpHeaders headers = response.getHeaders();
    //content length
    if (headers != null && headers.get("Content-Length") != null
        && !headers.get("Content-Length").isEmpty()) {
        List<String> contentLengthList = headers.get("Content-Length");
        String len = contentLengthList.get(0);
        sofaTracerSpan.setTag(CommonSpanTags.RESP_SIZE, Long.valueOf(len));
    }
    // current thread name
    sofaTracerSpan.setTag(CommonSpanTags.CURRENT_THREAD_NAME, Thread.currentThread().getName());
}
 
源代码4 项目: ByteJTA   文件: TransactionRequestInterceptor.java
private void invokeAfterRecvResponse(ClientHttpResponse httpResponse, boolean serverFlag) throws IOException {
	SpringCloudBeanRegistry beanRegistry = SpringCloudBeanRegistry.getInstance();
	TransactionBeanFactory beanFactory = beanRegistry.getBeanFactory();
	TransactionInterceptor transactionInterceptor = beanFactory.getTransactionInterceptor();

	HttpHeaders respHeaders = httpResponse.getHeaders();
	String respTransactionStr = respHeaders.getFirst(HEADER_TRANCACTION_KEY);
	String respPropagationStr = respHeaders.getFirst(HEADER_PROPAGATION_KEY);

	String transactionText = StringUtils.trimToNull(respTransactionStr);
	byte[] byteArray = StringUtils.isBlank(transactionText) ? null : Base64.getDecoder().decode(transactionText);
	TransactionContext serverContext = byteArray == null || byteArray.length == 0 //
			? null : (TransactionContext) SerializeUtils.deserializeObject(byteArray);

	TransactionResponseImpl txResp = new TransactionResponseImpl();
	txResp.setTransactionContext(serverContext);
	RemoteCoordinator serverCoordinator = beanRegistry.getConsumeCoordinator(respPropagationStr);
	txResp.setSourceTransactionCoordinator(serverCoordinator);
	txResp.setParticipantDelistFlag(serverFlag ? false : true);

	transactionInterceptor.afterReceiveResponse(txResp);
}
 
/**
 * This default implementation throws a {@link HttpClientErrorException} if the response status code
 * is {@link org.springframework.http.HttpStatus.Series#CLIENT_ERROR}, a {@link HttpServerErrorException}
 * if it is {@link org.springframework.http.HttpStatus.Series#SERVER_ERROR},
 * and a {@link RestClientException} in other cases.
 */
@Override
public void handleError(ClientHttpResponse response) throws IOException {
	HttpStatus statusCode = getHttpStatusCode(response);
	switch (statusCode.series()) {
		case CLIENT_ERROR:
			throw new HttpClientErrorException(statusCode, response.getStatusText(),
					response.getHeaders(), getResponseBody(response), getCharset(response));
		case SERVER_ERROR:
			throw new HttpServerErrorException(statusCode, response.getStatusText(),
					response.getHeaders(), getResponseBody(response), getCharset(response));
		default:
			throw new RestClientException("Unknown status code [" + statusCode + "]");
	}
}
 
源代码6 项目: lams   文件: DefaultResponseErrorHandler.java
/**
 * 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
 */
protected HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException {
	try {
		return response.getStatusCode();
	}
	catch (IllegalArgumentException ex) {
		throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(),
				response.getHeaders(), getResponseBody(response), getCharset(response));
	}
}
 
源代码7 项目: lams   文件: DefaultResponseErrorHandler.java
/**
 * This default implementation throws a {@link HttpClientErrorException} if the response status code
 * is {@link org.springframework.http.HttpStatus.Series#CLIENT_ERROR}, a {@link HttpServerErrorException}
 * if it is {@link org.springframework.http.HttpStatus.Series#SERVER_ERROR},
 * and a {@link RestClientException} in other cases.
 */
@Override
public void handleError(ClientHttpResponse response) throws IOException {
	HttpStatus statusCode = getHttpStatusCode(response);
	switch (statusCode.series()) {
		case CLIENT_ERROR:
			throw new HttpClientErrorException(statusCode, response.getStatusText(),
					response.getHeaders(), getResponseBody(response), getCharset(response));
		case SERVER_ERROR:
			throw new HttpServerErrorException(statusCode, response.getStatusText(),
					response.getHeaders(), getResponseBody(response), getCharset(response));
		default:
			throw new RestClientException("Unknown status code [" + statusCode + "]");
	}
}
 
/**
 * Determine the charset of the response (for inclusion in a status exception).
 * @param response the response to inspect
 * @return the associated charset, or {@code null} if none
 * @since 4.3.8
 */
@Nullable
protected Charset getCharset(ClientHttpResponse response) {
	HttpHeaders headers = response.getHeaders();
	MediaType contentType = headers.getContentType();
	return (contentType != null ? contentType.getCharset() : null);
}
 
源代码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);
}
 
protected ResponseExtractor<ResponseEntity<Void>> getAuthorizationResponseExtractor() {
    return new ResponseExtractor<ResponseEntity<Void>>() {
        public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException {
            return new ResponseEntity(response.getHeaders(), response.getStatusCode());
        }
    };
}
 
源代码11 项目: ByteTCC   文件: CompensableRequestInterceptor.java
private void invokeAfterRecvResponse(ClientHttpResponse httpResponse, boolean serverFlag) throws IOException {
	RemoteCoordinatorRegistry participantRegistry = RemoteCoordinatorRegistry.getInstance();
	SpringBootBeanRegistry beanRegistry = SpringBootBeanRegistry.getInstance();
	CompensableBeanFactory beanFactory = beanRegistry.getBeanFactory();
	TransactionInterceptor transactionInterceptor = beanFactory.getTransactionInterceptor();

	HttpHeaders respHeaders = httpResponse.getHeaders();
	String respTransactionStr = respHeaders.getFirst(HEADER_TRANCACTION_KEY);
	String respPropagationStr = respHeaders.getFirst(HEADER_PROPAGATION_KEY);
	String respRecursivelyStr = respHeaders.getFirst(HEADER_RECURSIVELY_KEY);

	String instanceId = StringUtils.trimToEmpty(respPropagationStr);

	RemoteAddr remoteAddr = CommonUtils.getRemoteAddr(instanceId);
	RemoteNode remoteNode = CommonUtils.getRemoteNode(instanceId);
	if (remoteAddr != null && remoteNode != null) {
		participantRegistry.putRemoteNode(remoteAddr, remoteNode);
	}

	String transactionText = StringUtils.trimToNull(respTransactionStr);
	byte[] byteArray = StringUtils.isBlank(transactionText) ? null : Base64.getDecoder().decode(transactionText);
	TransactionContext serverContext = byteArray == null || byteArray.length == 0 //
			? null
			: (TransactionContext) SerializeUtils.deserializeObject(byteArray);

	TransactionResponseImpl txResp = new TransactionResponseImpl();
	txResp.setTransactionContext(serverContext);
	RemoteCoordinator serverCoordinator = beanRegistry.getConsumeCoordinator(instanceId);
	txResp.setSourceTransactionCoordinator(serverCoordinator);
	txResp.setParticipantDelistFlag(serverFlag ? StringUtils.equalsIgnoreCase(respRecursivelyStr, "TRUE") : true);

	transactionInterceptor.afterReceiveResponse(txResp);
}
 
/**
 * 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);
}
 
/**
 * Determine the charset of the response (for inclusion in a status exception).
 * @param response the response to inspect
 * @return the associated charset, or {@code null} if none
 * @since 4.3.8
 */
@Nullable
protected Charset getCharset(ClientHttpResponse response) {
	HttpHeaders headers = response.getHeaders();
	MediaType contentType = headers.getContentType();
	return (contentType != null ? contentType.getCharset() : null);
}
 
private Charset getCharset(ClientHttpResponse response) {
	HttpHeaders headers = response.getHeaders();
	MediaType contentType = headers.getContentType();
	return contentType != null ? contentType.getCharSet() : null;
}
 
@Override
public void handleError(ClientHttpResponse response) throws IOException {
    if (!HttpStatus.Series.CLIENT_ERROR.equals(response.getStatusCode().series())) {
        errorHandler.handleError(response);
    } else {
        ClientHttpResponse bufferedResponse = new ClientHttpResponse() {
            private byte[] lazyBody;

            public HttpStatus getStatusCode() throws IOException {
                return response.getStatusCode();
            }

            public synchronized InputStream getBody() throws IOException {
                if (lazyBody == null) {
                    InputStream bodyStream = response.getBody();
                    if (bodyStream != null) {
                        lazyBody = FileCopyUtils.copyToByteArray(bodyStream);
                    } else {
                        lazyBody = new byte[0];
                    }
                }
                return new ByteArrayInputStream(lazyBody);
            }

            public HttpHeaders getHeaders() {
                return response.getHeaders();
            }

            public String getStatusText() throws IOException {
                return response.getStatusText();
            }

            public void close() {
                response.close();
            }

            public int getRawStatusCode() throws IOException {
                return this.getStatusCode().value();
            }
        };

        List<String> authenticateHeaders = bufferedResponse.getHeaders()
                .get(JwtSsoClientContext.HEADER_WWW_AUTHENTICATE);
        if (authenticateHeaders != null) {
            for (String authenticateHeader : authenticateHeaders) {
                if (authenticateHeader.startsWith(JwtSsoClientContext.PREFIX_BEARER_TOKEN)) {
                    throw new JwtSsoAccessTokenRequiredException("access token required.");
                }
            }
        }
        errorHandler.handleError(bufferedResponse);
    }

}
 
源代码16 项目: sdk-rest   文件: CustomResponseErrorHandler.java
private Charset getCharset(ClientHttpResponse response) {
    HttpHeaders headers = response.getHeaders();
    MediaType contentType = headers.getContentType();
    return contentType != null ? contentType.getCharSet() : null;
}
 
/**
 * HTTPステータスコード:4xx(クライアントエラー)に対応した例外をスローします。ステータスコードと例外の対応は以下のとおりです。
 * @param statusCode HTTPステータス
 * @param response HTTPレスポンンス
 * @throws IOException I/O例外
 */
protected void handleClientError(HttpStatus statusCode, ClientHttpResponse response) throws IOException {
    switch (statusCode) {
        case BAD_REQUEST:
            if (L.isDebugEnabled()) {
                L.debug(Strings.substitute(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0001"),
                    Maps.hash("status", statusCode.toString())
                        .map("message", getResponseBodyAsString(response))));
            }
            throw new BadRequestException(response.getHeaders(), getResponseBody(response), getCharset(response));
        case UNAUTHORIZED:
            if (L.isDebugEnabled()) {
                L.debug(Strings.substitute(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0002"),
                    Maps.hash("status", statusCode.toString())
                        .map("message", getResponseBodyAsString(response))));
            }
            throw new UnauthorizedException(response.getHeaders(), getResponseBody(response), getCharset(response));
        case FORBIDDEN:
            if (L.isDebugEnabled()) {
                L.debug(Strings.substitute(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0003"),
                    Maps.hash("status", statusCode.toString())
                        .map("message", getResponseBodyAsString(response))));
            }
            throw new ForbiddenException(response.getHeaders(), getResponseBody(response), getCharset(response));
        case NOT_FOUND:
            if (L.isDebugEnabled()) {
                L.debug(Strings.substitute(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0004"),
                    Maps.hash("status", statusCode.toString())
                        .map("message", getResponseBodyAsString(response))));
            }
            throw new NotFoundException(response.getHeaders(), getResponseBody(response), getCharset(response));
        case NOT_ACCEPTABLE:
            if (L.isDebugEnabled()) {
                L.debug(Strings.substitute(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0005"),
                    Maps.hash("status", statusCode.toString())
                        .map("message", getResponseBodyAsString(response))));
            }
            throw new NotAcceptableException(response.getHeaders(), getResponseBody(response), getCharset(response));
        case PROXY_AUTHENTICATION_REQUIRED:
            if (L.isDebugEnabled()) {
                L.debug(Strings.substitute(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0006"), 
                    Maps.hash("status", statusCode.toString())
                        .map("message", getResponseBodyAsString(response))));
            }
            throw new ProxyAuthenticationRequiredException(response.getHeaders(), getResponseBody(response),
                getCharset(response));
        case REQUEST_TIMEOUT:
            if (L.isDebugEnabled()) {
                L.debug(Strings.substitute(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0007"), 
                    Maps.hash("status", statusCode.toString())
                        .map("message", getResponseBodyAsString(response))));
            }
            throw new RequestTimeoutException(response.getHeaders(), getResponseBody(response), getCharset(response));
        case UNSUPPORTED_MEDIA_TYPE:
            if (L.isDebugEnabled()) {
                L.debug(Strings.substitute(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0008"),
                    Maps.hash("status", statusCode.toString())
                        .map("message", getResponseBodyAsString(response))));
            }
            throw new UnsupportedMediaTypeException(response.getHeaders(), getResponseBody(response), getCharset(response));
        case UNPROCESSABLE_ENTITY:
            if (L.isDebugEnabled()) {
                L.debug(Strings.substitute(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0009"), 
                    Maps.hash("status", statusCode.toString())
                        .map("message", getResponseBodyAsString(response))));
            }
            throw new UnprocessableEntityException(response.getHeaders(), getResponseBody(response), getCharset(response));
        default:
            if (L.isDebugEnabled()) {
                L.debug(Strings.substitute(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0010"), 
                    Maps.hash("status", statusCode.toString())
                        .map("message", getResponseBodyAsString(response))));
            }
            throw new HttpClientErrorException(statusCode, response.getStatusText(), response.getHeaders(),
                getResponseBody(response), getCharset(response));
    }
}
 
源代码18 项目: spring4-understanding   文件: RestTemplate.java
@Override
public HttpHeaders extractData(ClientHttpResponse response) throws IOException {
	return response.getHeaders();
}
 
/**
 * 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;
}
 
源代码20 项目: heimdall   文件: HeimdallResponseErrorHandler.java
/**
 * Determine the HTTP status of the given response.
 * <p>Note: Only called from {@link #handleError}, not from {@link #hasError}.
 * @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
 */
protected HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException {
	try {
		return response.getStatusCode();
	}
	catch (IllegalArgumentException ex) {
		throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(),
				response.getHeaders(), getResponseBody(response), getCharset(response));
	}
}