@SuppressWarnings("unchecked") private <E> Optional<E> readResponse(ResponseType<E> type) { final Type responseType = type.getType(); try { // check InputStream if (InputStream.class == responseType) { return (Optional<E>) Optional.ofNullable(response.getBody().getInputStream()); } if (Void.class != responseType) { ResponseExtractor<E> extractor = new HttpMessageConverterExtractor<>(responseType, getMessageConverters()); return Optional.ofNullable(extractor.extractData(httpResponse)); } } catch (Exception e) { throw new HttpEntityProcessingException("Failed to read HTTP entity as [" + type + "]", e); } return Optional.empty(); }
@Override public Exception decode(String methodKey, Response response) { if((response.status() >= 200 && response.status() < 300) || response.status()==HttpStatus.BAD_REQUEST.value() || response.status()==HttpStatus.INTERNAL_SERVER_ERROR.value() ){ try { HttpMessageConverterExtractor<SimpleDataResult<Object>> extractor = new HttpMessageConverterExtractor<SimpleDataResult<Object>>(SimpleDataResult.class, this.httpMessageConverters.getConverters()); SimpleDataResult<Object> result = extractor.extractData(new FeignResponseAdapter(response)); log.error("error code: {}, result: {}", response.status(), result); //防止普通异常也被熔断,if not convert as HystrixBadRequestException and fallback also throws error, it will be enabled short-circuited get "Hystrix circuit short-circuited and is OPEN" when client frequently invoke if(result!=null){ return new HystrixBadRequestException(result.getMessage(), new ServiceException(result.getMessage(), result.getCode())); } } catch (IOException e) { throw new BaseException("error feign response : " + e.getMessage(), e); } } Exception exception = defaultDecoder.decode(methodKey, response); return exception; }
private static String getJson(RestTemplate restTemplate, String urlString) { ClientHttpResponse response = null; HttpMethod method = null; try { method = HttpMethod.GET; URI url = new UriTemplate(urlString).expand(); ClientHttpRequest request = restTemplate.getRequestFactory().createRequest(url, method); List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>(); acceptableMediaTypes.add(MediaType.APPLICATION_JSON); request.getHeaders().setAccept(acceptableMediaTypes ); //if (requestCallback != null) { // requestCallback.doWithRequest(request); //} response = request.execute(); if (response.getBody() != null) { HttpMessageConverterExtractor<String> extractor = new HttpMessageConverterExtractor<String>(String.class, restTemplate.getMessageConverters()); String data = extractor.extractData(response); return data; }; } catch (IOException ex) { throw new ResourceAccessException("I/O error on " + method.name() + " request for \"" + urlString + "\":" + ex.getMessage(), ex); } finally { if (response != null) { response.close(); } } return null; }
@SuppressWarnings({ "unchecked", "rawtypes" }) protected <T> T decodeByType(FeignResponseAdapter response, Type type) throws IOException, FeignException { HttpMessageConverterExtractor<SimpleDataResult> extractor = new HttpMessageConverterExtractor( type, this.messageConverters.getObject().getConverters()); T dr = (T)extractor.extractData(response); return dr; }
@Override public Object decode(final Response response, Type type) throws IOException, FeignException { if (type instanceof Class || type instanceof ParameterizedType || type instanceof WildcardType) { @SuppressWarnings({ "unchecked", "rawtypes" }) HttpMessageConverterExtractor<?> extractor = new HttpMessageConverterExtractor( type, this.messageConverters.getObject().getConverters()); return extractor.extractData(new FeignResponseAdapter(response)); } throw new DecodeException( "type is not an instance of Class or ParameterizedType: " + type); }
protected final <T> T extractData(ClientHttpResponse response, Class<T> cls) throws IOException { notNull(response, "response"); notNull(cls, "cls"); if (Void.class.isAssignableFrom(cls)) { return null; } return new HttpMessageConverterExtractor<>(cls, restTemplate.getMessageConverters()).extractData(response); }
public VndErrorResponseErrorHandler(List<HttpMessageConverter<?>> messageConverters) { errorExtractor = new HttpMessageConverterExtractor<VndErrors>(VndErrors.class, messageConverters); }
public VndErrorResponseErrorHandler(List<HttpMessageConverter<?>> messageConverters) { vndErrorsExtractor = new HttpMessageConverterExtractor<VndErrors>(VndErrors.class, messageConverters); vndErrorExtractor = new HttpMessageConverterExtractor<VndError>(VndError.class, messageConverters); }
private <I> I readBody(final Type type, final ClientHttpResponse response) throws IOException { final ResponseExtractor<I> extractor = new HttpMessageConverterExtractor<>(type, converters); return extractor.extractData(response); }
protected <T> T execute(String url, final Object data, HttpMethod method, Class<T> responseType, Map<String, ?> urlParams) { return template.execute(url, method, new HttpEntityRequestCallback(data), new HttpMessageConverterExtractor<T>(responseType, template.getMessageConverters()), urlParams); }
public ResponseErrorHandler(List<HttpMessageConverter<?>> messageConverters) { gdcErrorExtractor = new HttpMessageConverterExtractor<>(ErrorStructure.class, noNullElements(messageConverters, "messageConverters")); }
protected ResponseExtractor<OAuth2AccessToken> getResponseExtractor() { getRestTemplate(); // force initialization return new HttpMessageConverterExtractor<OAuth2AccessToken>(OAuth2AccessToken.class, this.messageConverters); }
public void handleError(final ClientHttpResponse response) throws IOException { if (! HttpStatus.Series.CLIENT_ERROR.equals(response.getStatusCode().series())) { // We should only care about 400 level errors. Ex: A 500 server error shouldn't // be an oauth related error. errorHandler.handleError(response); } else { // Need to use buffered response because input stream may need to be consumed multiple times. 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); } } 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 response.getRawStatusCode(); } }; try { HttpMessageConverterExtractor<OAuth2Exception> extractor = new HttpMessageConverterExtractor<OAuth2Exception>( OAuth2Exception.class, messageConverters); try { OAuth2Exception body = extractor.extractData(bufferedResponse); if (body != null) { // If we can get an OAuth2Exception already from the body, it is likely to have more information than // the header does, so just re-throw it here. throw body; } } catch (RestClientException e) { // ignore } // first try: www-authenticate error List<String> authenticateHeaders = bufferedResponse.getHeaders().get("WWW-Authenticate"); if (authenticateHeaders != null) { for (String authenticateHeader : authenticateHeaders) { maybeThrowExceptionFromHeader(authenticateHeader, OAuth2AccessToken.BEARER_TYPE); maybeThrowExceptionFromHeader(authenticateHeader, OAuth2AccessToken.OAUTH2_TYPE); } } // then delegate to the custom handler errorHandler.handleError(bufferedResponse); } catch (OAuth2Exception ex) { if (bufferedResponse.getRawStatusCode() == 401 || ! ex.getClass().equals(OAuth2Exception.class)) { // Status code 401 should always mean that we need a legitimate token. // Caught a specific, derived class so this is not just some generic error throw ex; } else { // This is not an exception that is really understood, so allow our delegate // to handle it in a non-oauth way errorHandler.handleError(bufferedResponse); } } } }