本文整理汇总了Java中org.springframework.web.client.DefaultResponseErrorHandler类的典型用法代码示例。如果您正苦于以下问题:Java DefaultResponseErrorHandler类的具体用法?Java DefaultResponseErrorHandler怎么用?Java DefaultResponseErrorHandler使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
DefaultResponseErrorHandler类属于org.springframework.web.client包,在下文中一共展示了DefaultResponseErrorHandler类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createRequest
import org.springframework.web.client.DefaultResponseErrorHandler; //导入依赖的package包/类
/**
* Method to create http requests to services
*/
public default <I, O> ListenableFuture<ResponseEntity<O>> createRequest(final URIBuilder uri,
final HttpMethod method, final I body, final Class<O> returnClazz, final HttpHeaders header) {
final AsyncRestTemplate restTemplate = new AsyncRestTemplate();
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
if (header != null) {
header.setContentType(MediaType.APPLICATION_JSON);
}
HttpEntity<?> entity;
if (body != null) {
entity = new HttpEntity<I>(body, header);
} else {
entity = new HttpEntity<String>(null, header);
}
return restTemplate.exchange(uri.toString(), method, entity, returnClazz);
}
示例2: SearchResource
import org.springframework.web.client.DefaultResponseErrorHandler; //导入依赖的package包/类
/**
* Create the search proxy with the given elasticsearch host url.
*
* @param elasticSearchConnectionUrl the elasticsearch host url
*/
@Autowired
@SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
public SearchResource(String elasticSearchConnectionUrl)
throws UnsupportedEncodingException, MalformedURLException {
this.connectionUrl = elasticSearchConnectionUrl;
URL url = new URL(elasticSearchConnectionUrl);
restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
restTemplate.getMessageConverters()
.add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
String credentials = url.getUserInfo();
if (!StringUtils.isEmpty(credentials)) {
byte[] plainCredsBytes = credentials.getBytes("UTF-8");
byte[] base64CredsBytes = Base64.encode(plainCredsBytes);
base64Credentials = new String(base64CredsBytes, "UTF-8");
}
// prevent throwing exception on error codes
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
protected boolean hasError(HttpStatus statusCode) {
return false;
}
});
}
示例3: init
import org.springframework.web.client.DefaultResponseErrorHandler; //导入依赖的package包/类
public void init() {
HATEOAS_MEDIA_TYPE = MediaType.parseMediaType("application/hal+json");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.registerModule(new Jackson2HalModule());
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(HATEOAS_MEDIA_TYPE));
converter.setObjectMapper(mapper);
hateoasRestTemplate = new RestTemplate(Arrays.<HttpMessageConverter<?>> asList(converter));
hateoasRestTemplate.setErrorHandler(new DefaultResponseErrorHandler());
//restTemplate = new RestTemplate(Arrays.<HttpMessageConverter<?>> asList(new MappingJackson2HttpMessageConverter()));
//restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
}
示例4: FacebookTokenServices
import org.springframework.web.client.DefaultResponseErrorHandler; //导入依赖的package包/类
public FacebookTokenServices() {
restTemplate = new RestTemplate();
((RestTemplate) restTemplate).setErrorHandler(new DefaultResponseErrorHandler() {
@Override
// Ignore 400
public void handleError(
ClientHttpResponse response )
throws IOException {
if (response.getRawStatusCode() != 400) {
super.handleError(response);
}
}
});
}
示例5: testInvalidCredentials
import org.springframework.web.client.DefaultResponseErrorHandler; //导入依赖的package包/类
@Test
@OAuth2ContextConfiguration(resource = InvalidClientCredentials.class, initialize = false)
public void testInvalidCredentials() throws Exception {
context.setAccessTokenProvider(new ClientCredentialsAccessTokenProvider() {
@Override
protected ResponseErrorHandler getResponseErrorHandler() {
return new DefaultResponseErrorHandler() {
public void handleError(ClientHttpResponse response) throws IOException {
responseHeaders = response.getHeaders();
responseStatus = response.getStatusCode();
}
};
}
});
try {
context.getAccessToken();
fail("Expected ResourceAccessException");
}
catch (Exception e) {
// ignore
}
// System.err.println(responseHeaders);
String header = responseHeaders.getFirst("WWW-Authenticate");
assertTrue("Wrong header: " + header, header.contains("Basic realm"));
assertEquals(HttpStatus.UNAUTHORIZED, responseStatus);
}
示例6: handleError
import org.springframework.web.client.DefaultResponseErrorHandler; //导入依赖的package包/类
public void handleError() {
// handle error2
RestTemplate client = new RestTemplate();
ResponseErrorHandler responseErrorHandler = new DefaultResponseErrorHandler() {
@Override
public void handleError(ClientHttpResponse response)
throws IOException {
LOGGER.warn("response status: '{}', headers: '{}'",
response.getStatusCode(), response.getHeaders());
}
};
client.setErrorHandler(responseErrorHandler);
client.exchange("http://localhost:8080/person/denied", HttpMethod.GET,
null, String.class);
}
示例7: initRestTemplate
import org.springframework.web.client.DefaultResponseErrorHandler; //导入依赖的package包/类
/**
* springboot初始化restTemplate
*/
@Bean
public RestTemplate initRestTemplate() {
// 长连接保持30秒
PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);
// 总连接数
pollingConnectionManager.setMaxTotal(1000);
// 同路由的并发数
pollingConnectionManager.setDefaultMaxPerRoute(1000);
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setConnectionManager(pollingConnectionManager);
// 重试次数,默认是3次,没有开启
httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));
// 保持长连接配置,需要在头添加Keep-Alive
httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());
RequestConfig.Builder builder = RequestConfig.custom();
builder.setConnectionRequestTimeout(200);
builder.setConnectTimeout(5000);
builder.setSocketTimeout(5000);
RequestConfig requestConfig = builder.build();
httpClientBuilder.setDefaultRequestConfig(requestConfig);
List<Header> headers = new ArrayList<>();
headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
headers.add(new BasicHeader("Accept-Language", "zh-CN"));
headers.add(new BasicHeader("Connection", "Keep-Alive"));
httpClientBuilder.setDefaultHeaders(headers);
HttpClient httpClient = httpClientBuilder.build();
// httpClient连接配置,底层是配置RequestConfig
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
// 连接超时
clientHttpRequestFactory.setConnectTimeout(5000);
// 数据读取超时时间,即SocketTimeout
clientHttpRequestFactory.setReadTimeout(5000);
// 连接不够用的等待时间,不宜过长,必须设置,比如连接不够用时,时间过长将是灾难性的
clientHttpRequestFactory.setConnectionRequestTimeout(200);
// 缓冲请求数据,默认值是true。通过POST或者PUT大量发送数据时,建议将此属性更改为false,以免耗尽内存。
clientHttpRequestFactory.setBufferRequestBody(false);
// 添加内容转换器
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
messageConverters.add(initStringHttpMessageConverter());
messageConverters.add(new FormHttpMessageConverter());
messageConverters.add(new MappingJackson2XmlHttpMessageConverter());
messageConverters.add(new MappingJackson2HttpMessageConverter());
RestTemplate restTemplate = new RestTemplate(messageConverters);
restTemplate.setRequestFactory(clientHttpRequestFactory);
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
return restTemplate;
}
示例8: setup
import org.springframework.web.client.DefaultResponseErrorHandler; //导入依赖的package包/类
@Before
public void setup() {
testRest.getRestTemplate().setErrorHandler(new DefaultResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return response.getStatusCode() != HttpStatus.OK;
}
});
testRest.getRestTemplate().setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter(mapper)));
}
示例9: getRestTemplate
import org.springframework.web.client.DefaultResponseErrorHandler; //导入依赖的package包/类
/**
* Gets the rest template.
*
* @return the rest template
*/
private RestTemplate getRestTemplate() {
if (restTemplate == null) {
restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create()
.setDefaultHeaders(Arrays.asList(getBasicAuthenticateHeader()))
.build()));
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
log.error("Response error: {} {}", response.getStatusCode(), response.getStatusText());
ErrorResponse errorResponse = null;
try {
errorResponse = objectMapper.readValue(response.getBody(), ErrorResponse.class);
} catch (IOException ioe) {
log.error("Fail to parse error", ioe);
}
if (errorResponse != null) {
log.error("Response error object: {}", errorResponse);
throw new ScalablePressBadRequestException(errorResponse);
}
super.handleError(response);
}
});
}
return restTemplate;
}
示例10: GitHubClient
import org.springframework.web.client.DefaultResponseErrorHandler; //导入依赖的package包/类
private GitHubClient(String accessToken) {
this.restTemplate = new RestTemplate();
this.restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
String errorMessage = "Unable to load Github Data:" + new String(getResponseBody(response), Charsets.UTF_8);
LOGGER.error(errorMessage);
throw new AuthenticationServiceException(errorMessage);
}
});
this.restTemplate.getInterceptors().add((request, body, execution) -> {
request.getHeaders().add("Authorization", "bearer " + accessToken);
return execution.execute(request, body);
});
}
示例11: TestRestTemplate
import org.springframework.web.client.DefaultResponseErrorHandler; //导入依赖的package包/类
/**
* Create a new {@link TestRestTemplate} instance with the specified credentials.
* @param username the username to use (or {@code null})
* @param password the password (or {@code null})
* @param httpClientOptions client options to use if the Apache HTTP Client is used
*/
public TestRestTemplate(String username, String password,
HttpClientOption... httpClientOptions) {
if (ClassUtils.isPresent("org.apache.http.client.config.RequestConfig", null)) {
setRequestFactory(
new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions));
}
addAuthentication(username, password);
setErrorHandler(new DefaultResponseErrorHandler() {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
});
}
开发者ID:vikrammane23,项目名称:https-github.com-g0t4-jenkins2-course-spring-boot,代码行数:21,代码来源:TestRestTemplate.java
示例12: AssertingRestTemplate
import org.springframework.web.client.DefaultResponseErrorHandler; //导入依赖的package包/类
public AssertingRestTemplate() {
setErrorHandler(new DefaultResponseErrorHandler() {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
if (hasError(response)) {
log.error("Response has status code [" + response.getStatusCode() + "] and text [" + response.getStatusText() + "])");
}
}
});
}
示例13: getRestTemplate
import org.springframework.web.client.DefaultResponseErrorHandler; //导入依赖的package包/类
private RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
});
return restTemplate;
}
示例14: getRestTemplate
import org.springframework.web.client.DefaultResponseErrorHandler; //导入依赖的package包/类
protected RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
log.error(response.getStatusText());
}
});
return restTemplate;
}
示例15: testInvalidCredentialsWithFormAuthentication
import org.springframework.web.client.DefaultResponseErrorHandler; //导入依赖的package包/类
@Test
@OAuth2ContextConfiguration(resource = InvalidClientCredentials.class, initialize = false)
public void testInvalidCredentialsWithFormAuthentication() throws Exception {
resource.setClientAuthenticationScheme(AuthenticationScheme.form);
context.setAccessTokenProvider(new ClientCredentialsAccessTokenProvider() {
@Override
protected ResponseErrorHandler getResponseErrorHandler() {
return new DefaultResponseErrorHandler() {
public void handleError(ClientHttpResponse response) throws IOException {
responseHeaders = response.getHeaders();
responseStatus = response.getStatusCode();
}
};
}
});
try {
context.getAccessToken();
fail("Expected ResourceAccessException");
}
catch (Exception e) {
// ignore
}
// System.err.println(responseHeaders);
String header = responseHeaders.getFirst("WWW-Authenticate");
assertTrue("Wrong header: " + header, header.contains("Form realm"));
assertEquals(HttpStatus.UNAUTHORIZED, responseStatus);
}