當前位置: 首頁>>代碼示例>>Java>>正文


Java DefaultResponseErrorHandler類代碼示例

本文整理匯總了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);
}
 
開發者ID:stefanstaniAIM,項目名稱:IPPR2016,代碼行數:21,代碼來源:Caller.java

示例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;
    }
  });
}
 
開發者ID:dzhw,項目名稱:metadatamanagement,代碼行數:28,代碼來源:SearchResource.java

示例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());
}
 
開發者ID:ssouporg,項目名稱:denv,代碼行數:18,代碼來源:DenvClient.java

示例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);
			}
		}
	});
}
 
開發者ID:locationtech,項目名稱:geowave,代碼行數:15,代碼來源:FacebookTokenServices.java

示例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);
}
 
開發者ID:jungyang,項目名稱:oauth-client-master,代碼行數:27,代碼來源:ClientCredentialsProviderTests.java

示例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);
}
 
開發者ID:spotlight2001,項目名稱:itsme,代碼行數:18,代碼來源:MyRestClient.java

示例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;

}
 
開發者ID:wu05281,項目名稱:admin-shiro,代碼行數:62,代碼來源:RestTemplateConfig.java

示例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)));
}
 
開發者ID:taboola,項目名稱:taboola-cronyx,代碼行數:11,代碼來源:CronyxRestControllerIntegrationTest.java

示例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;
}
 
開發者ID:gcauchis,項目名稱:ScalablePress4J,代碼行數:33,代碼來源:AbstractRestApi.java

示例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);
    });
}
 
開發者ID:reportportal,項目名稱:service-authorization,代碼行數:16,代碼來源:GitHubClient.java

示例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() + "])");
			}
		}
	});
}
 
開發者ID:reshmik,項目名稱:Zipkin,代碼行數:11,代碼來源:AssertingRestTemplate.java

示例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;
}
 
開發者ID:sbuettner,項目名稱:spring-boot-autoconfigure-wro4j,代碼行數:12,代碼來源:IntegrationTest.java

示例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;
}
 
開發者ID:Kurento,項目名稱:kurento-java,代碼行數:11,代碼來源:BaseRepositoryTest.java

示例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);
}
 
開發者ID:jungyang,項目名稱:oauth-client-master,代碼行數:28,代碼來源:ClientCredentialsProviderTests.java


注:本文中的org.springframework.web.client.DefaultResponseErrorHandler類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。