本文整理匯總了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);
}