org.springframework.test.context.jdbc.Sql#org.springframework.web.client.HttpClientErrorException源码实例Demo

下面列出了org.springframework.test.context.jdbc.Sql#org.springframework.web.client.HttpClientErrorException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: restful-booker-platform   文件: AuthRequests.java
public boolean postCheckAuth(String tokenValue){
    Token token = new Token(tokenValue);

    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_JSON);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

    HttpEntity<Token> httpEntity = new HttpEntity<>(token, requestHeaders);

    try{
        ResponseEntity<String> response = restTemplate.exchange(host + "/auth/validate", HttpMethod.POST, httpEntity, String.class);
        return response.getStatusCodeValue() == 200;
    } catch (HttpClientErrorException e){
        return false;
    }
}
 
源代码2 项目: jsets-shiro-demo   文件: StatelessTestAction.java
@RequestMapping("/jwt_post")
  public @ResponseBody BaseResponse jwtPost(
  						 @RequestParam(name="apiName") String apiName
  						,@RequestParam(name="jwt") String jwt
  						,HttpServletRequest request) {
  	
MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
form.add("jwt", jwt); 
   try{
   	String restPostUrl = request.getRequestURL().toString().replace("stateless/jwt_post", "");
   	restPostUrl += "jwt_api/"+apiName;
   	RestTemplate restTemplate = new RestTemplate();
   	String result = restTemplate.postForObject(restPostUrl, form, String.class);
   	return BaseResponse.ok().message(result);
   }catch(HttpClientErrorException e){
       return BaseResponse.fail().message(e.getResponseBodyAsString());
   }
  }
 
源代码3 项目: jsets-shiro-demo   文件: StatelessTestAction.java
@RequestMapping("/hmac_post")
  public @ResponseBody BaseResponse hmacPost(
  		@RequestParam(name="apiName") String apiName
  		,@RequestParam(name="parameter1") String parameter1
	,@RequestParam(name="parameter2") String parameter2
	,@RequestParam(name="hmac_app_id") String hmac_app_id
	,@RequestParam(name="hmac_timestamp") long hmac_timestamp
	,@RequestParam(name="hmac_digest") String hmac_digest
	,HttpServletRequest request) {
  	
MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
form.add("parameter1", parameter1); 
form.add("parameter2", parameter2); 
   form.add("hmac_app_id", hmac_app_id); 
   form.add("hmac_timestamp", hmac_timestamp); 
   form.add("hmac_digest", hmac_digest); 
   try{
   	String restPostUrl = request.getRequestURL().toString().replace("stateless/hmac_post", "");
   	restPostUrl += "hmac_api/"+apiName;
   	RestTemplate restTemplate = new RestTemplate();
   	String result = restTemplate.postForObject(restPostUrl, form, String.class);
       return BaseResponse.ok().message(result);
   }catch(HttpClientErrorException e){
       return BaseResponse.fail().message(e.getResponseBodyAsString());
   }
  }
 
源代码4 项目: cubeai   文件: OAuth2AuthenticationServiceTest.java
private void mockRefreshGrant() {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", "refresh_token");
    params.add("refresh_token", REFRESH_TOKEN_VALUE);
    //we must authenticate with the UAA server via HTTP basic authentication using the browser's client_id with no client secret
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", CLIENT_AUTHORIZATION);
    HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);
    OAuth2AccessToken newAccessToken = createAccessToken(NEW_ACCESS_TOKEN_VALUE, NEW_REFRESH_TOKEN_VALUE);
    when(restTemplate.postForEntity("http://uaa/oauth/token", entity, OAuth2AccessToken.class))
        .thenReturn(new ResponseEntity<OAuth2AccessToken>(newAccessToken, HttpStatus.OK));
    //headers missing -> unauthorized
    HttpEntity<MultiValueMap<String, String>> headerlessEntity = new HttpEntity<>(params, new HttpHeaders());
    when(restTemplate.postForEntity("http://uaa/oauth/token", headerlessEntity, OAuth2AccessToken.class))
        .thenThrow(new HttpClientErrorException(HttpStatus.UNAUTHORIZED));
}
 
源代码5 项目: OAuth-2.0-Cookbook   文件: UserDashboard.java
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");
    }
}
 
private Map<String, Object> postForMap(String path, MultiValueMap<String, String> formData, HttpHeaders headers) {
    if (headers.getContentType() == null) {
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    }
    @SuppressWarnings("rawtypes")
    Map map = new HashMap();
    try {
        map = restTemplate.exchange(path, HttpMethod.POST,
                new HttpEntity<MultiValueMap<String, String>>(formData, headers), Map.class).getBody();
    } catch (HttpClientErrorException e1) {
        logger.error("catch token exception when check token!", e1);
        map.put(ERROR, e1.getStatusCode());

    } catch (HttpServerErrorException e2) {
        logger.error("catch no permission exception when check token!", e2);
        map.put(ERROR, e2.getStatusCode());

    } catch (Exception e) {
        logger.error("catch common exception when check token!", e);
    }

    @SuppressWarnings("unchecked")
    Map<String, Object> result = map;
    return result;
}
 
private Manifest getManifest(String name, String reference) {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(
            new MediaType("application", "vnd.docker.distribution.manifest.v2+json"),
            new MediaType("application", "vnd.docker.distribution.manifest.v2+prettyjws")
    ));
    HttpEntity entity = new HttpEntity<>(headers);
    URI uri = forName(name).path("/manifests/").path(reference).build().toUri();
    try {
        ResponseEntity<Manifest> exchange = getRestTemplate().exchange(uri, HttpMethod.GET, entity, Manifest.class);
        return exchange.getBody();
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
            return null;
        }
        log.error("can't fetch manifest from {} by {}", uri, e.getMessage());
        throw e;
    }
}
 
源代码8 项目: spring-data-cosmosdb   文件: TelemetrySender.java
private ResponseEntity<String> executeRequest(final TelemetryEventData eventData) {
    final HttpHeaders headers = new HttpHeaders();

    headers.add(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON.toString());

    try {
        final RestTemplate restTemplate = new RestTemplate();
        final HttpEntity<String> body = new HttpEntity<>(MAPPER.writeValueAsString(eventData), headers);

        return restTemplate.exchange(TELEMETRY_TARGET_URL, HttpMethod.POST, body, String.class);
    } catch (JsonProcessingException | HttpClientErrorException ignore) {
        log.warn("Failed to exchange telemetry request, {}.", ignore.getMessage());
    }

    return null;
}
 
源代码9 项目: mojito   文件: SmartlingClient.java
public void deleteFile(String projectId, String fileUri) {

        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("fileUri", fileUri);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        try {
            Response response = oAuth2RestTemplate.postForObject(API_FILES_DELETE, requestEntity, Response.class, projectId);
            throwExceptionOnError(response, ERROR_CANT_DELETE_FILE, fileUri);
        } catch(HttpClientErrorException e) {
            throw wrapIntoSmartlingException(e, ERROR_CANT_DELETE_FILE, fileUri);
        }
    }
 
源代码10 项目: taskana   文件: TaskCommentControllerIntTest.java
@Disabled("Disabled until Authorization check is up!")
@Test
void should_FailToCreateTaskComment_When_TaskIsNotVisible() {

  TaskCommentRepresentationModel taskCommentRepresentationModelToCreate =
      new TaskCommentRepresentationModel();
  taskCommentRepresentationModelToCreate.setTaskId("TKI:000000000000000000000000000000000000");
  taskCommentRepresentationModelToCreate.setTextField("newly created task comment");

  ThrowingCallable httpCall =
      () -> {
        template.exchange(
            restHelper.toUrl(
                Mapping.URL_TASK_GET_POST_COMMENTS, "TKI:000000000000000000000000000000000000"),
            HttpMethod.POST,
            new HttpEntity<>(
                taskCommentRepresentationModelToCreate, restHelper.getHeadersUser_1_1()),
            ParameterizedTypeReference.forType(TaskCommentRepresentationModel.class));
      };
  assertThatThrownBy(httpCall)
      .extracting(ex -> ((HttpClientErrorException) ex).getStatusCode())
      .isEqualTo(HttpStatus.FORBIDDEN);
}
 
源代码11 项目: secure-data-service   文件: RESTClient.java
/**
 * Make a PUT request to a REST service
 * 
 * @param path
 *            the unique portion of the requested REST service URL
 * @param token
 *            not used yet
 * 
 * @param entity
 *            entity used for update
 * 
 * @throws NoSessionException
 */
public void putJsonRequestWHeaders(String path, String token, Object entity) {
    
    if (token != null) {
        URLBuilder url = null;
        if (!path.startsWith("http")) {
            url = new URLBuilder(getSecurityUrl());
            url.addPath(path);
        } else {
            url = new URLBuilder(path);
        }
        
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + token);
        headers.add("Content-Type", "application/json");
        HttpEntity requestEntity = new HttpEntity(entity, headers);
        LOGGER.debug("Updating API at: {}", url);
        try {
            template.put(url.toString(), requestEntity);
        } catch (HttpClientErrorException e) {
            LOGGER.debug("Catch HttpClientException: {}", e.getStatusCode());
        }
    }
}
 
源代码12 项目: openapi-generator   文件: UserApi.java
/**
 * Creates list of users with given input array
 * 
 * <p><b>0</b> - successful operation
 * @param body List of user object (required)
 * @return ResponseEntity&lt;Void&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Void> createUsersWithListInputWithHttpInfo(List<User> body) throws RestClientException {
    Object postBody = body;
    
    // verify the required parameter 'body' is set
    if (body == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUsersWithListInput");
    }
    
    String path = apiClient.expandPath("/user/createWithList", Collections.<String, Object>emptyMap());

    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
    final MultiValueMap formParams = new LinkedMultiValueMap();

    final String[] accepts = { };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] {  };

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
源代码13 项目: api-layer   文件: AbstractZosmfService.java
/**
 * Method handles exception from REST call to z/OSMF into internal exception. It convert original exception into
 * custom one with better messages and types for subsequent treatment.
 *
 * @param url URL of invoked REST endpoint
 * @param re original exception
 * @return translated exception
 */
protected RuntimeException handleExceptionOnCall(String url, RuntimeException re) {
    if (re instanceof ResourceAccessException) {
        apimlLog.log("org.zowe.apiml.security.serviceUnavailable", url, re.getMessage());
        return new ServiceNotAccessibleException("Could not get an access to z/OSMF service.");
    }

    if (re instanceof HttpClientErrorException.Unauthorized) {
        return new BadCredentialsException("Username or password are invalid.");
    }

    if (re instanceof RestClientException) {
        apimlLog.log("org.zowe.apiml.security.generic", re.getMessage(), url);
        return new AuthenticationServiceException("A failure occurred when authenticating.", re);
    }

    return re;
}
 
源代码14 项目: restful-booker-platform   文件: AuthRequests.java
public boolean postCheckAuth(String tokenValue){
    Token token = new Token(tokenValue);

    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_JSON);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

    HttpEntity<Token> httpEntity = new HttpEntity<>(token, requestHeaders);

    try{
        ResponseEntity<String> response = restTemplate.exchange(host + "/auth/validate", HttpMethod.POST, httpEntity, String.class);
        return response.getStatusCodeValue() == 200;
    } catch (HttpClientErrorException e){
        return false;
    }
}
 
源代码15 项目: restful-booker-platform   文件: AuthRequests.java
public boolean postCheckAuth(String tokenValue){
    Token token = new Token(tokenValue);

    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_JSON);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

    HttpEntity<Token> httpEntity = new HttpEntity<Token>(token, requestHeaders);

    try{
        ResponseEntity<String> response = restTemplate.exchange(host + "/auth/validate", HttpMethod.POST, httpEntity, String.class);
        return response.getStatusCodeValue() == 200;
    } catch (HttpClientErrorException e){
        return false;
    }
}
 
@Test
void testThrowsExceptionIfInvalidFilterIsUsed() {
  ThrowingCallable httpCall =
      () ->
          template.exchange(
              restHelper.toUrl(Mapping.URL_WORKBASKET_ACCESS_ITEMS)
                  + "?sort-by=workbasket-key&order=asc&page=1&page-size=9&invalid=user-1-1",
              HttpMethod.GET,
              restHelper.defaultRequest(),
              WORKBASKET_ACCESS_ITEM_PAGE_MODEL_TYPE);
  assertThatThrownBy(httpCall)
      .isInstanceOf(HttpClientErrorException.class)
      .hasMessageContaining("[invalid]")
      .extracting(ex -> ((HttpClientErrorException) ex).getStatusCode())
      .isEqualTo(HttpStatus.BAD_REQUEST);
}
 
/**
 * Sends a refresh grant to the token endpoint using the current refresh token to obtain new tokens.
 *
 * @param refreshTokenValue the refresh token to use to obtain new tokens.
 * @return the new, refreshed access token.
 */
@Override
public OAuth2AccessToken sendRefreshGrant(String refreshTokenValue) {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", "refresh_token");
    params.add("refresh_token", refreshTokenValue);
    HttpHeaders headers = new HttpHeaders();
    addAuthentication(headers, params);
    HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);
    log.debug("contacting OAuth2 token endpoint to refresh OAuth2 JWT tokens");
    ResponseEntity<OAuth2AccessToken> responseEntity = restTemplate.postForEntity(getTokenEndpoint(), entity,
                                                                                  OAuth2AccessToken.class);
    if (responseEntity.getStatusCode() != HttpStatus.OK) {
        log.debug("failed to refresh tokens: {}", responseEntity.getStatusCodeValue());
        throw new HttpClientErrorException(responseEntity.getStatusCode());
    }
    OAuth2AccessToken accessToken = responseEntity.getBody();
    log.info("refreshed OAuth2 JWT cookies using refresh_token grant");
    return accessToken;
}
 
源代码18 项目: x-pipe   文件: RetryNTimesTest.java
@Test
public void testGetOriginalException() {
	assertTrue(RetryNTimes.getOriginalException(new IOException("test")) instanceof IOException);
	assertTrue(RetryNTimes.getOriginalException(
			new ExecutionException(new IllegalArgumentException("test"))) instanceof IllegalArgumentException);
	assertTrue(RetryNTimes.getOriginalException(new ExecutionException(null)) instanceof ExecutionException);
	assertTrue(RetryNTimes.getOriginalException(new ExecutionException(new InvocationTargetException(
			new HttpClientErrorException(HttpStatus.BAD_REQUEST, "test")))) instanceof HttpClientErrorException);
	assertTrue(RetryNTimes.getOriginalException(
			new ExecutionException(new InvocationTargetException(null))) instanceof InvocationTargetException);
	assertTrue(RetryNTimes.getOriginalException(new InvocationTargetException(new IOException("test"))) instanceof IOException);
	assertTrue(RetryNTimes.getOriginalException(new InvocationTargetException(null)) instanceof InvocationTargetException);

	assertFalse(RetryNTimes.getOriginalException(
			new InvocationTargetException(new IOException())) instanceof InvocationTargetException);
	assertFalse(RetryNTimes.getOriginalException(new ExecutionException(
			new InvocationTargetException(new IOException("test")))) instanceof ExecutionException);
}
 
源代码19 项目: tutorials   文件: PetApi.java
/**
 * Add a new pet to the store
 * 
 * <p><b>405</b> - Invalid input
 * @param body Pet object that needs to be added to the store
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public void addPet(Pet body) throws RestClientException {
    Object postBody = body;
    
    // verify the required parameter 'body' is set
    if (body == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling addPet");
    }
    
    String path = UriComponentsBuilder.fromPath("/pet").build().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 = { 
        "application/xml", "application/json"
    };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { 
        "application/json", "application/xml"
    };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] { "petstore_auth" };

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
 
源代码20 项目: mojito   文件: SmartlingClient.java
public void createBindings(Bindings bindings, String projectId) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
    HttpEntity<Bindings> requestEntity = new HttpEntity<>(bindings, headers);
    try {
        String s = oAuth2RestTemplate.postForObject(API_BINDINGS, requestEntity, String.class, projectId);
        logger.debug("create binding: {}", s);
    } catch(HttpClientErrorException e) {
        throw wrapIntoSmartlingException(e, ERROR_CANT_CREATE_BINDINGS, objectMapper.writeValueAsStringUnchecked(bindings));
    }
}
 
@Override
public T get(ID id, Object... uriVariables) throws FirebaseRepositoryException {
    ReflectionUtils.makeAccessible(documentId);

    HttpEntity httpEntity = HttpEntityBuilder.create(firebaseObjectMapper, firebaseApplicationService).build();
    T response = restTemplate.exchange(getDocumentPath(id), HttpMethod.GET, httpEntity, documentClass, uriVariables).getBody();
    if (response == null) {
        throw new HttpClientErrorException(HttpStatus.NOT_FOUND);
    } else {
        ReflectionUtils.setField(documentId, response, id);
        return response;
    }
}
 
@Test
void testFailOnImportDuplicates() throws Exception {
  ClassificationRepresentationModel classification =
      this.getClassificationWithKeyAndDomain("L110105", "DOMAIN_A");

  TaskanaPagedModel<ClassificationRepresentationModel> clList =
      new TaskanaPagedModel<>(
          TaskanaPagedModelKeys.CLASSIFICATIONS, Arrays.asList(classification, classification));

  assertThatThrownBy(() -> importRequest(clList))
      .isInstanceOf(HttpClientErrorException.class)
      .extracting(ex -> ((HttpClientErrorException) ex).getStatusCode())
      .isEqualTo(HttpStatus.CONFLICT);
}
 
源代码23 项目: apollo   文件: NamespaceControllerTest.java
@Test
public void create() {
  try {
    NamespaceDTO namespaceDTO = new NamespaceDTO();
    namespaceDTO.setClusterName("cluster");
    namespaceDTO.setNamespaceName("invalid name");
    namespaceDTO.setAppId("whatever");
    restTemplate.postForEntity(
        url("/apps/{appId}/clusters/{clusterName}/namespaces"),
        namespaceDTO, NamespaceDTO.class, namespaceDTO.getAppId(), namespaceDTO.getClusterName());
    Assert.fail("Should throw");
  } catch (HttpClientErrorException e) {
    Assert.assertThat(new String(e.getResponseBodyAsByteArray()), containsString(InputValidator.INVALID_CLUSTER_NAMESPACE_MESSAGE));
  }
}
 
源代码24 项目: gdax-java   文件: GdaxExchangeImpl.java
@Override
public <T, R> T post(String resourcePath,  ParameterizedTypeReference<T> responseType, R jsonObj) {
    String jsonBody = toJson(jsonObj);

    try {
        ResponseEntity<T> response = restTemplate.exchange(getBaseUrl() + resourcePath,
                HttpMethod.POST,
                securityHeaders(resourcePath, "POST", jsonBody),
                responseType);
        return response.getBody();
    } catch (HttpClientErrorException ex) {
        log.error("POST request Failed for '" + resourcePath + "': " + ex.getResponseBodyAsString());
    }
    return null;
}
 
@Test
void should_returnBadRequest_ifAccessIdIsOrganizationalGroup() {
  String parameters = "?access-id=cn=organisationseinheit ksc,cn=organisation,ou=test,o=taskana";
  ThrowingCallable httpCall =
      () ->
          template.exchange(
              restHelper.toUrl(Mapping.URL_WORKBASKET_ACCESS_ITEMS) + parameters,
              HttpMethod.DELETE,
              restHelper.defaultRequest(),
              ParameterizedTypeReference.forType(Void.class));
  assertThatThrownBy(httpCall)
      .isInstanceOf(HttpClientErrorException.class)
      .extracting(ex -> ((HttpClientErrorException) ex).getStatusCode())
      .isEqualTo(HttpStatus.BAD_REQUEST);
}
 
@Test
public void preFlightRequestWithCorsRejected() throws Exception {
	try {
		this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
		performOptions("/cors-restricted", this.headers, String.class);
		fail();
	}
	catch (HttpClientErrorException e) {
		assertEquals(HttpStatus.FORBIDDEN, e.getStatusCode());
	}
}
 
源代码27 项目: apollo   文件: CtripUserServiceTest.java
@Test(expected = HttpClientErrorException.class)
public void testSearchUsersWithError() throws Exception {
  when(restTemplate.exchange(eq(someUserServiceUrl), eq(HttpMethod.POST), any(HttpEntity.class),
      eq(someResponseType)))
      .thenThrow(new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR));

  String someKeyword = "someKeyword";
  int someOffset = 0;
  int someLimit = 10;

  ctripUserService.searchUsers(someKeyword, someOffset, someLimit);
}
 
源代码28 项目: api-framework   文件: Booking.java
public static ResponseEntity<String> getBooking(int id, MediaType accept) throws HttpClientErrorException {
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAccept(Collections.singletonList(accept));

    HttpEntity<String> httpEntity = new HttpEntity<String>(requestHeaders);

    return restTemplate.exchange(baseUrl + "/booking/" + Integer.toString(id), HttpMethod.GET, httpEntity, String.class);
}
 
源代码29 项目: cubeai   文件: AbilityService.java
public ResponseEntity<String> apiGateway(String url, String requestBody, MultiValueMap<String,String> requestHeader) {
    log.debug("Start API forwarding");

    try {
        HttpEntity<String> httpEntity = new HttpEntity<>(requestBody, requestHeader);
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); // 直接使用RestTemplate的POST方法时,字符串默认使用“ISO-8859-1”编码,需要转换
        ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);
        return ResponseEntity.status(response.getStatusCodeValue()).body(response.getBody());
    } catch(HttpClientErrorException e) {
        return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsString());
    }
}
 
源代码30 项目: tutorials   文件: UserApi.java
/**
 * Updated user
 * This can only be done by the logged in user.
 * <p><b>400</b> - Invalid user supplied
 * <p><b>404</b> - User not found
 * @param username name that need to be updated (required)
 * @param body Updated user object (required)
 * @return ResponseEntity&lt;Void&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Void> updateUserWithHttpInfo(String username, User body) throws RestClientException {
    Object postBody = body;

    // verify the required parameter 'username' is set
    if (username == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling updateUser");
    }

    // verify the required parameter 'body' is set
    if (body == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling updateUser");
    }

    // create path and map variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("username", username);
    String path = apiClient.expandPath("/user/{username}", uriVariables);

    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
    final MultiValueMap formParams = new LinkedMultiValueMap();

    final String[] accepts = { };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = {
        "application/json"
    };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] {  };

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}