本文整理汇总了Java中org.springframework.web.client.HttpClientErrorException类的典型用法代码示例。如果您正苦于以下问题:Java HttpClientErrorException类的具体用法?Java HttpClientErrorException怎么用?Java HttpClientErrorException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HttpClientErrorException类属于org.springframework.web.client包,在下文中一共展示了HttpClientErrorException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: tryToGetUserProfile
import org.springframework.web.client.HttpClientErrorException; //导入依赖的package包/类
private void tryToGetUserProfile(ModelAndView mv, String token) {
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Authorization", "Bearer " + token);
String endpoint = "http://localhost:8080/api/profile";
try {
RequestEntity<Object> request = new RequestEntity<>(
headers, HttpMethod.GET, URI.create(endpoint));
ResponseEntity<UserProfile> userProfile = restTemplate.exchange(request, UserProfile.class);
if (userProfile.getStatusCode().is2xxSuccessful()) {
mv.addObject("profile", userProfile.getBody());
} else {
throw new RuntimeException("it was not possible to retrieve user profile");
}
} catch (HttpClientErrorException e) {
throw new RuntimeException("it was not possible to retrieve user profile");
}
}
示例2: create
import org.springframework.web.client.HttpClientErrorException; //导入依赖的package包/类
public Topic create(String name) {
if (repository.findByName(name).isPresent()) {
throw new HttpClientErrorException(HttpStatus.CONFLICT, name + " 이미 등록된 태그 입니다.");
}
return repository.save(new Topic(name));
}
示例3: getWorkOrdersHttpErrTest
import org.springframework.web.client.HttpClientErrorException; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Test(priority=14)
/** again with http error */
public void getWorkOrdersHttpErrTest(){
CmsDeployment cmsDeployment = mock(CmsDeployment.class);
when(cmsDeployment.getDeploymentId()).thenReturn(DPLMNT_ID);
DelegateExecution delegateExecution = mock(DelegateExecution.class);
when(delegateExecution.getVariable("dpmt")).thenReturn(cmsDeployment);
//we rely on mock of restTemplate to give error answer
RestTemplate httpErrorTemplate = mock(RestTemplate.class);
when(
httpErrorTemplate.getForObject(anyString(),
any(java.lang.Class.class), anyLong(), anyInt()))
.thenThrow(
new HttpClientErrorException(HttpStatus.I_AM_A_TEAPOT,"mocking"));
cc.setRestTemplate(httpErrorTemplate);
cc.getWorkOrderIds(delegateExecution);
//it would be nice to assert the exec was updated, but for now we
//just let the test pass if the client swallows the http error
}
示例4: getChecksum
import org.springframework.web.client.HttpClientErrorException; //导入依赖的package包/类
private String getChecksum(String defaultValue, String url,
String version) {
String result = defaultValue;
if (result == null && StringUtils.hasText(url)) {
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
HttpComponentsClientHttpRequestFactory requestFactory
= new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
url = constructUrl(url, version);
try {
ResponseEntity<String> response
= new RestTemplate(requestFactory).exchange(
url, HttpMethod.GET, null, String.class);
if (response.getStatusCode().equals(HttpStatus.OK)) {
result = response.getBody();
}
}
catch (HttpClientErrorException httpException) {
// no action necessary set result to undefined
logger.debug("Didn't retrieve checksum because", httpException);
}
}
return result;
}
示例5: completeConnection
import org.springframework.web.client.HttpClientErrorException; //导入依赖的package包/类
/**
* Complete the connection to the OAuth2 provider.
*
* @param connectionFactory the service provider's connection factory e.g. FacebookConnectionFactory
* @param request the current web request
* @return a new connection to the service provider
*/
public Connection completeConnection(OAuth2ConnectionFactory<?> connectionFactory, NativeWebRequest request) {
if (connectionFactory.supportsStateParameter()) {
verifyStateParameter(request);
}
String code = request.getParameter("code");
try {
AccessGrant accessGrant = connectionFactory.getOAuthOperations()
.exchangeForAccess(code, callbackUrl(request), null);
return connectionFactory.createConnection(accessGrant);
} catch (HttpClientErrorException e) {
log.warn("HttpClientErrorException while completing connection: " + e.getMessage());
log.warn(" Response body: " + e.getResponseBodyAsString());
throw e;
}
}
示例6: apiApplicationsByApplicationNameGet
import org.springframework.web.client.HttpClientErrorException; //导入依赖的package包/类
/**
*
*
* <p><b>200</b> - Success
* @param applicationName The applicationName parameter
* @return HierarchicalModel
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public HierarchicalModel apiApplicationsByApplicationNameGet(String applicationName) throws RestClientException {
Object postBody = null;
// verify the required parameter 'applicationName' is set
if (applicationName == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'applicationName' when calling apiApplicationsByApplicationNameGet");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("applicationName", applicationName);
String path = UriComponentsBuilder.fromPath("/api/applications/{applicationName}").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
final String[] accepts = {
"text/plain", "application/json", "text/json"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { };
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<HierarchicalModel> returnType = new ParameterizedTypeReference<HierarchicalModel>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
示例7: attend
import org.springframework.web.client.HttpClientErrorException; //导入依赖的package包/类
@Transactional
public void attend(Meeting meeting, User user) {
if (!Meeting.MeetingStatus.PUBLISHED.equals(meeting.getMeetingStatus())) {
throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "참여 불가능한 모입니다.");
}
if (!meeting.onRegistTime()) throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "참여 가능한 시간이 아닙니다.");
if (meeting.isAttendBy(user)) {
throw new HttpClientErrorException(HttpStatus.CONFLICT, "이미 참여한 모임입니다.");
}
if (meeting.getMaxAttendees() <= 0 || meeting.getAttendees().size() >= meeting.getMaxAttendees()) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "참여 할 수 없습니다. 참여 인원을 확인하세요.");
}
meeting.attendBy(user);
repository.save(meeting);
}
示例8: getNamespaceId
import org.springframework.web.client.HttpClientErrorException; //导入依赖的package包/类
private long getNamespaceId(NamespaceIdentifier namespaceIdentifier) {
String appId = namespaceIdentifier.getAppId();
String clusterName = namespaceIdentifier.getClusterName();
String namespaceName = namespaceIdentifier.getNamespaceName();
Env env = namespaceIdentifier.getEnv();
NamespaceDTO namespaceDTO = null;
try {
namespaceDTO = namespaceAPI.loadNamespace(appId, env, clusterName, namespaceName);
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
throw new BadRequestException(String.format(
"namespace not exist. appId:%s, env:%s, clusterName:%s, namespaceName:%s", appId, env, clusterName,
namespaceName));
}
}
return namespaceDTO.getId();
}
示例9: getRaw
import org.springframework.web.client.HttpClientErrorException; //导入依赖的package包/类
/**
* Get newsposts from the api.
*
* @param args [0] = source, [1] = type, [2] = clean name
* @return NewsSource object containing list of articles and source information
*/
public NewsSource getRaw(String... args) {
NewsSource newsSource = null;
String url = apiUrl
+ "?source=" + args[0]
+ "&sortBy=" + args[1]
+ "&apiKey=" + apiKey;
try {
newsSource = restTemplate.getForObject(url, NewsSource.class);
newsSource.setSourceName(args[2]);
logger.info("received " + newsSource.getArticles().size() + " articles from " + args[0]);
} catch (HttpClientErrorException ex) {
logger.error("Bad Request", ex);
}
return newsSource;
}
示例10: testErrorsSerializedAsJsonApi
import org.springframework.web.client.HttpClientErrorException; //导入依赖的package包/类
@Test
public void testErrorsSerializedAsJsonApi() throws IOException {
RestTemplate testRestTemplate = new RestTemplate();
try {
testRestTemplate
.getForEntity("http://localhost:" + this.port + "/doesNotExist", String.class);
Assert.fail();
}
catch (HttpClientErrorException e) {
assertEquals(HttpStatus.NOT_FOUND, e.getStatusCode());
String body = e.getResponseBodyAsString();
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(JacksonModule.createJacksonModule());
Document document = mapper.readerFor(Document.class).readValue(body);
Assert.assertEquals(1, document.getErrors().size());
ErrorData errorData = document.getErrors().get(0);
Assert.assertEquals("404", errorData.getStatus());
Assert.assertEquals("Not Found", errorData.getTitle());
Assert.assertEquals("No message available", errorData.getDetail());
}
}
示例11: create
import org.springframework.web.client.HttpClientErrorException; //导入依赖的package包/类
/**
* Handle a POST method by creating a new Milkshake.
* Queries appropriate fruit service to check for inventory and consume the fruit into the milkshake
*
* @param flavor to create
* @return a newly created Milkshake
*/
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody Milkshake create(@RequestParam Flavor flavor) {
try {
FlavorProvider provider = getFlavorProvider(flavor);
provider.getIngredients();
} catch (IngredientException e) {
throw new HttpClientErrorException(HttpStatus.TOO_MANY_REQUESTS, e.getMessage());
}
Milkshake milkshake = new Milkshake();
milkshake.setId(counter.incrementAndGet());
milkshake.setFlavor(flavor);
return milkshake;
}
示例12: getAndValidateGameStateChange
import org.springframework.web.client.HttpClientErrorException; //导入依赖的package包/类
private LibraryEntity getAndValidateGameStateChange(Authentication user, Long libraryId, LibraryGameData data) {
LibraryEntity entity = libraryRepository.findOne(libraryId);
if (entity == null) {
throw new HttpClientErrorException(NOT_FOUND, format("No library game exists with id '%d'.", libraryId));
}
validateLibraryIsUsers(user, entity.getOwner().getId());
if (entity.getState() == GameState.ON_LOAN) {
throw new HttpClientErrorException(BAD_REQUEST,
format("You can't modify '%s' while it is loaned to '%s'.",
entity.getGame().getName(),
entity.getBorrower().getName()));
}
if (data.getAttributes().getState() == GameState.ON_LOAN) {
throw new HttpClientErrorException(BAD_REQUEST,
format("You can't set '%s' to an on-loan state.", entity.getGame().getName()));
}
return entity;
}
示例13: run
import org.springframework.web.client.HttpClientErrorException; //导入依赖的package包/类
@Override
protected RestResponsePage<Approval> run() throws Exception {
try {
ParameterizedTypeReference<RestResponsePage<Approval>>
responsetype =
new ParameterizedTypeReference<RestResponsePage<Approval>>() {
};
ResponseEntity<RestResponsePage<Approval>>
result =
restTemplate
.exchange(uriBuilder.build().encode().toUri(), HttpMethod.POST,
new HttpEntity<>(approvalFilters), responsetype);
return result.getBody();
} catch (HttpClientErrorException exception) {
throw new HystrixBadRequestException(exception.getMessage(),
new HttpBadRequestException(ErrorResponse.getErrorResponse(exception), exception));
}
}
示例14: getActuatorVersion
import org.springframework.web.client.HttpClientErrorException; //导入依赖的package包/类
public ActuatorVersion getActuatorVersion(Application app) {
String url = app.endpoints().env();
try {
LOGGER.debug("HEAD {}", url);
HttpHeaders headers = headRestTemplate.headForHeaders(new URI(url));
return ActuatorVersion.parse(headers.getContentType());
} catch (RestClientException ex) {
if(ex instanceof HttpClientErrorException) {
HttpClientErrorException clientEx = ((HttpClientErrorException)ex);
// Spring Boot 1.3 does not allow HEAD method, so let's assume the app is up
if(clientEx.getStatusCode() == HttpStatus.METHOD_NOT_ALLOWED) {
return ActuatorVersion.V1;
}
}
throw RestTemplateErrorHandler.handle(app, url, ex);
} catch (URISyntaxException e) {
throw RestTemplateErrorHandler.handle(app, e);
}
}
示例15: updateWoStateTestHttperr
import org.springframework.web.client.HttpClientErrorException; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public void updateWoStateTestHttperr(){
DelegateExecution delegateExecution = mock(DelegateExecution.class);
CmsDeployment cmsDeployment = mock(CmsDeployment.class);
when(delegateExecution.getVariable("dpmt")).thenReturn(cmsDeployment);
when(delegateExecution.getId()).thenReturn("Id11");
when(delegateExecution.getVariable("error-message")).thenReturn("mocked-error");
CmsWorkOrderSimple cmsWorkOrderSimple= new CmsWorkOrderSimple();
cmsWorkOrderSimple.setDpmtRecordId(0);
cmsWorkOrderSimple.setDeploymentId(66);
cmsWorkOrderSimple.setComments("mockito-mock-comments");
RestTemplate httpErrorTemplate = mock(RestTemplate.class);
when(
httpErrorTemplate.getForObject(anyString(),
any(java.lang.Class.class), anyLong(), anyInt()))
.thenThrow(
new HttpClientErrorException(HttpStatus.I_AM_A_TEAPOT,"mocking"));
cc.setRestTemplate(httpErrorTemplate);
cc.updateWoState(delegateExecution, cmsWorkOrderSimple, "failed") ; //also to do complete
}