Java Code Examples for org.springframework.http.client.ClientHttpResponse#getHeaders()

The following examples show how to use org.springframework.http.client.ClientHttpResponse#getHeaders() . 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: DCTMJaxbErrorHandler.java    From documentum-rest-client-java with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 2
Source File: TransactionRequestInterceptor.java    From ByteJTA with GNU Lesser General Public License v3.0 6 votes vote down vote up
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);
}
 
Example 3
Source File: CompensableRequestInterceptor.java    From ByteTCC with GNU Lesser General Public License v3.0 6 votes vote down vote up
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);
}
 
Example 4
Source File: RestTemplateInterceptor.java    From sofa-tracer with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example 5
Source File: DefaultResponseErrorHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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 + "]");
	}
}
 
Example 6
Source File: DefaultResponseErrorHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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));
	}
}
 
Example 7
Source File: DefaultResponseErrorHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 + "]");
	}
}
 
Example 8
Source File: DefaultResponseErrorHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example 9
Source File: RestResponseErrorHandler.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 10
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
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());
        }
    };
}
 
Example 11
Source File: CompensableRequestInterceptor.java    From ByteTCC with GNU Lesser General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 12
Source File: DefaultResponseErrorHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example 13
Source File: DefaultResponseErrorHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example 14
Source File: DefaultResponseErrorHandler.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
private Charset getCharset(ClientHttpResponse response) {
	HttpHeaders headers = response.getHeaders();
	MediaType contentType = headers.getContentType();
	return contentType != null ? contentType.getCharSet() : null;
}
 
Example 15
Source File: RestTemplate.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public HttpHeaders extractData(ClientHttpResponse response) throws IOException {
	return response.getHeaders();
}
 
Example 16
Source File: RestClientResponseErrorHandler.java    From sinavi-jfw with Apache License 2.0 4 votes vote down vote up
/**
 * 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));
    }
}
 
Example 17
Source File: CustomResponseErrorHandler.java    From sdk-rest with MIT License 4 votes vote down vote up
private Charset getCharset(ClientHttpResponse response) {
    HttpHeaders headers = response.getHeaders();
    MediaType contentType = headers.getContentType();
    return contentType != null ? contentType.getCharSet() : null;
}
 
Example 18
Source File: JwtSsoResponseErrorHandler.java    From wecube-platform with Apache License 2.0 4 votes vote down vote up
@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);
    }

}
 
Example 19
Source File: DefaultResponseErrorHandler.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * 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;
}
 
Example 20
Source File: HeimdallResponseErrorHandler.java    From heimdall with Apache License 2.0 3 votes vote down vote up
/**
 * 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));
	}
}