当前位置: 首页>>代码示例>>Java>>正文


Java RequestEntity类代码示例

本文整理汇总了Java中org.springframework.http.RequestEntity的典型用法代码示例。如果您正苦于以下问题:Java RequestEntity类的具体用法?Java RequestEntity怎么用?Java RequestEntity使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


RequestEntity类属于org.springframework.http包,在下文中一共展示了RequestEntity类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getUserInfoFor

import org.springframework.http.RequestEntity; //导入依赖的package包/类
public Map<String, String> getUserInfoFor(OAuth2AccessToken accessToken) {
    RestTemplate restTemplate = new RestTemplate();

    RequestEntity<Void> requestEntity = new RequestEntity<>(
            getHeader(accessToken.getValue()),
            HttpMethod.GET,
            URI.create(properties.getUserInfoUri())
    );

    ParameterizedTypeReference<Map<String, String>> typeRef =
            new ParameterizedTypeReference<Map<String, String>>() {};
    ResponseEntity<Map<String, String>> result = restTemplate.exchange(
            requestEntity, typeRef);

    if (result.getStatusCode().is2xxSuccessful()) {
        return result.getBody();
    }

    throw new RuntimeException("It wasn't possible to retrieve userInfo");
}
 
开发者ID:PacktPublishing,项目名称:OAuth-2.0-Cookbook,代码行数:21,代码来源:UserInfoService.java

示例2: getUserInfoFor

import org.springframework.http.RequestEntity; //导入依赖的package包/类
public Map<String, String> getUserInfoFor(OAuth2AccessToken accessToken) {
    RestTemplate restTemplate = new RestTemplate();

    RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(
            getHeader(accessToken),
            HttpMethod.GET,
            URI.create("https://www.googleapis.com/oauth2/v3/userinfo")
    );

    ResponseEntity<Map> result = restTemplate.exchange(
            requestEntity, Map.class);

    if (result.getStatusCode().is2xxSuccessful()) {
        return result.getBody();
    }

    throw new RuntimeException("It wasn't possible to retrieve userInfo");
}
 
开发者ID:PacktPublishing,项目名称:OAuth-2.0-Cookbook,代码行数:19,代码来源:UserInfoService.java

示例3: accessServiceUsingRestTemplate

import org.springframework.http.RequestEntity; //导入依赖的package包/类
@Test
public void accessServiceUsingRestTemplate() {

	// Access root resource

	URI uri = URI.create(String.format(SERVICE_URI, port));
	RequestEntity<Void> request = RequestEntity.get(uri).accept(HAL_JSON).build();
	Resource<Object> rootLinks = restOperations.exchange(request, new ResourceType<Object>() {}).getBody();
	Links links = new Links(rootLinks.getLinks());

	// Follow stores link

	Link storesLink = links.getLink("stores").expand();
	request = RequestEntity.get(URI.create(storesLink.getHref())).accept(HAL_JSON).build();
	Resources<Store> stores = restOperations.exchange(request, new ResourcesType<Store>() {}).getBody();

	stores.getContent().forEach(store -> log.info("{} - {}", store.name, store.address));
}
 
开发者ID:Just-Fun,项目名称:spring-data-examples,代码行数:19,代码来源:StarbucksClient.java

示例4: tryToGetUserProfile

import org.springframework.http.RequestEntity; //导入依赖的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");
    }
}
 
开发者ID:PacktPublishing,项目名称:OAuth-2.0-Cookbook,代码行数:22,代码来源:UserDashboard.java

示例5: testSimple

import org.springframework.http.RequestEntity; //导入依赖的package包/类
@Test
public void testSimple() throws Exception {

    final Map<String, Object> body = new HashMap<>();
    body.put("foo", "Hello, world!");
    body.put("bar", 12345);
    body.put("baz", "2017-02-10");
    body.put("qux", Collections.emptyList());

    final RequestEntity<Map<String, Object>> requestEntity = RequestEntity
            .post(new UriTemplate(url).expand(port))
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON)
            .body(body);
    final ParameterizedTypeReference<Map<String, Object>> responseType = new ParameterizedTypeReference<Map<String, Object>>() {
    };
    final ResponseEntity<Map<String, Object>> response = restTemplate.exchange(requestEntity,
            responseType);

    assertThat(response.getBody(), is(body));
}
 
开发者ID:backpaper0,项目名称:spring-boot-vue-simple-sample,代码行数:22,代码来源:JsonSampleControllerTest.java

示例6: invokeAPI

import org.springframework.http.RequestEntity; //导入依赖的package包/类
/**
 * Invoke API by sending HTTP request with the given options.
 *
 * @param <T> the return type to use
 * @param path The sub-path of the HTTP URL
 * @param method The request method
 * @param queryParams The query parameters
 * @param body The request body object
 * @param headerParams The header parameters
 * @param formParams The form parameters
 * @param accept The request's Accept header
 * @param contentType The request's Content-Type header
 * @param authNames The authentications to apply
 * @param returnType The return type into which to deserialize the response
 * @return The response body in chosen type
 */
public <T> T invokeAPI(String path, HttpMethod method, MultiValueMap<String, String> queryParams, Object body, HttpHeaders headerParams, MultiValueMap<String, Object> formParams, List<MediaType> accept, MediaType contentType, String[] authNames, ParameterizedTypeReference<T> returnType) throws RestClientException {
    updateParamsForAuth(authNames, queryParams, headerParams);
    
    final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(path);
    if (queryParams != null) {
        builder.queryParams(queryParams);
    }
    
    final BodyBuilder requestBuilder = RequestEntity.method(method, builder.build().toUri());
    if(accept != null) {
        requestBuilder.accept(accept.toArray(new MediaType[accept.size()]));
    }
    if(contentType != null) {
        requestBuilder.contentType(contentType);
    }
    
    addHeadersToRequest(headerParams, requestBuilder);
    addHeadersToRequest(defaultHeaders, requestBuilder);
    
    RequestEntity<Object> requestEntity = requestBuilder.body(selectBody(body, formParams, contentType));

    ResponseEntity<T> responseEntity = restTemplate.exchange(requestEntity, returnType);
    
    statusCode = responseEntity.getStatusCode();
    responseHeaders = responseEntity.getHeaders();

    if (responseEntity.getStatusCode() == HttpStatus.NO_CONTENT) {
        return null;
    } else if (responseEntity.getStatusCode().is2xxSuccessful()) {
        if (returnType == null) {
            return null;
        }
        return responseEntity.getBody();
    } else {
        // The error handler built into the RestTemplate should handle 400 and 500 series errors.
        throw new RestClientException("API returned " + statusCode + " and it wasn't handled by the RestTemplate error handler");
    }
}
 
开发者ID:jopache,项目名称:Settings,代码行数:55,代码来源:ApiClient.java

示例7: getToken

import org.springframework.http.RequestEntity; //导入依赖的package包/类
public OAuth2Token getToken(String authorizationCode) {
    RestTemplate rest = new RestTemplate();
    String authBase64 = configuration.encodeCredentials("clientapp",
            "123456");

    RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(
        configuration.getBody(authorizationCode),
        configuration.getHeader(authBase64), HttpMethod.POST,
        URI.create("http://localhost:8080/oauth/token"));

    ResponseEntity<OAuth2Token> responseEntity = rest.exchange(
            requestEntity, OAuth2Token.class);

    if (responseEntity.getStatusCode().is2xxSuccessful()) {
        return responseEntity.getBody();
    }

    throw new RuntimeException("error trying to retrieve access token");
}
 
开发者ID:PacktPublishing,项目名称:OAuth-2.0-Cookbook,代码行数:20,代码来源:AuthorizationCodeTokenService.java

示例8: testPushTaupageLog

import org.springframework.http.RequestEntity; //导入依赖的package包/类
@Test
public void testPushTaupageLog() throws Exception {
    final TestRestTemplate restOperations = new TestRestTemplate(CORRECT_USER, CORRECT_PASSWORD);

    stubFor(post(urlPathEqualTo("/api/instance-logs")).willReturn(aResponse().withStatus(201)));

    final URI url = URI.create("http://localhost:" + port + "/instance-logs");
    final ResponseEntity<String> response = restOperations.exchange(
            RequestEntity.post(url).contentType(APPLICATION_JSON).body(
                    instanceLogsPayload), String.class);
    assertThat(response.getStatusCode()).isEqualTo(CREATED);

    log.debug("Waiting for async tasks to finish");
    TimeUnit.SECONDS.sleep(1);

    verify(postRequestedFor(urlPathEqualTo("/api/instance-logs"))
                   .withRequestBody(equalToJson(intanceLogsJsonPayload))
                   .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890")));

    verify(putRequestedFor(urlPathEqualTo("/events/" + eventID))
                   .withRequestBody(equalToJson(new String(auditTrailJsonPayload)))
                   .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890")));

    log.info("METRICS:\n{}",
             restOperations.getForObject("http://localhost:" + managementPort + "/metrics", String.class));
}
 
开发者ID:zalando-stups,项目名称:log-sink,代码行数:27,代码来源:LogSinkAppIT.java

示例9: main

import org.springframework.http.RequestEntity; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
  RestTemplate template = new RestTemplate();
  template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
  MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
  headers.add("X-Tenant-Name", "default");

  RequestEntity<String> requestEntity = new RequestEntity<String>(headers, HttpMethod.GET,
      new URI("http://127.0.0.1:9980/registry/v3/microservices"));
  ResponseEntity<String> stringResponseEntity = template.exchange(requestEntity, String.class);
  System.out.println(stringResponseEntity.getBody());
  ResponseEntity<MicroserviceArray> microseriveResponseEntity = template
      .exchange(requestEntity, MicroserviceArray.class);
  MicroserviceArray microserives = microseriveResponseEntity.getBody();
  System.out.println(microserives.getServices().get(1).getServiceId());

  // instance
  headers.add("X-ConsumerId", microserives.getServices().get(1).getServiceId());
  requestEntity = new RequestEntity<String>(headers, HttpMethod.GET,
      new URI("http://127.0.0.1:9980/registry/v3/microservices/" + microserives.getServices().get(1).getServiceId()
          + "/instances"));
  ResponseEntity<String> microserviceInstanceResponseEntity = template.exchange(requestEntity, String.class);
  System.out.println(microserviceInstanceResponseEntity.getBody());
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:24,代码来源:ServiceCenterExample.java

示例10: exchangeUsingParameterizedTypeWithUnderlyingRestTemplate

import org.springframework.http.RequestEntity; //导入依赖的package包/类
@Test
public void exchangeUsingParameterizedTypeWithUnderlyingRestTemplate() {
  ParameterizedTypeReference<List<String>> typeReference = new ParameterizedTypeReference<List<String>>() {
  };
  ResponseEntity<List<String>> actual;

  for (HttpMethod method : httpMethods) {
    when(underlying.exchange(url, method, requestEntity, typeReference, param1, param2)).thenReturn(typedResponse);
    actual = wrapper.exchange(url, method, requestEntity, typeReference, param1, param2);
    assertThat(actual, is(typedResponse));
    verify(underlying).exchange(url, method, requestEntity, typeReference, param1, param2);

    when(underlying.exchange(url, method, requestEntity, typeReference, paramsMap)).thenReturn(typedResponse);
    actual = wrapper.exchange(url, method, requestEntity, typeReference, paramsMap);
    assertThat(actual, is(typedResponse));
    verify(underlying).exchange(url, method, requestEntity, typeReference, paramsMap);

    when(underlying.exchange(uri, method, requestEntity, typeReference)).thenReturn(typedResponse);
    actual = wrapper.exchange(uri, method, requestEntity, typeReference);
    assertThat(actual, is(typedResponse));
    verify(underlying).exchange(uri, method, requestEntity, typeReference);

    RequestEntity<String> request = new RequestEntity<>(method, uri);
    when(underlying.exchange(request, typeReference)).thenReturn(typedResponse);
    actual = wrapper.exchange(request, typeReference);
    assertThat(actual, is(typedResponse));
    verify(underlying).exchange(request, typeReference);
  }
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:30,代码来源:TestRestTemplateWrapper.java

示例11: saveEntry

import org.springframework.http.RequestEntity; //导入依赖的package包/类
@PostMapping(value= {"/{dicId}/entries", "/{dicId}/entries/{fieldId}"})
public String saveEntry(@PathVariable("dicId") Long dicId
		, RequestEntity<DictionaryEntry> data
		, Map<String, Object> model) {
	Dictionary dictionaryEntity  = null;
	DictionaryEntry entry = data.getBody();
	if (entry.getId() != null) {
		dictionaryEntity = this.dictionaryService.updateEntry(dicId, entry);
	} else {
		dictionaryEntity = this.dictionaryService.addEntry(dicId, entry);
	}
	model.put("dictionaryEntity", dictionaryEntity);
	return "tool/dictionary_entries";
}
 
开发者ID:Kevin-Huang-NZ,项目名称:springboot-jsp-generator,代码行数:15,代码来源:DictionaryController.java

示例12: save

import org.springframework.http.RequestEntity; //导入依赖的package包/类
@PostMapping(value = "/")
public ResponseEntity<Tables> save(RequestEntity<Tables> data) {
	Tables tableEntity = null;
	if (data.getBody().getId() != null) {
		tableEntity = this.tableService.update(data.getBody());
	} else {
		tableEntity = this.tableService.save(data.getBody());
	}
	return ResponseEntity.accepted().body(tableEntity);
}
 
开发者ID:Kevin-Huang-NZ,项目名称:springboot-jsp-generator,代码行数:11,代码来源:TableController.java

示例13: saveField

import org.springframework.http.RequestEntity; //导入依赖的package包/类
@PostMapping(value= {"/{tableId}/fields", "/{tableId}/fields/{fieldId}"})
public String saveField(@PathVariable("tableId") Long tableId
		, RequestEntity<TableField> data
		, Map<String, Object> model) {
	Tables tableEntity = null;
	TableField field = data.getBody();
	if (field.getId() != null) {
		tableEntity = this.tableService.updateField(tableId, field);
	} else {
		tableEntity = this.tableService.addField(tableId, field);
	}
	model.put("tableEntity", tableEntity);
	return "tool/table_fields";
}
 
开发者ID:Kevin-Huang-NZ,项目名称:springboot-jsp-generator,代码行数:15,代码来源:TableController.java

示例14: updateRelease

import org.springframework.http.RequestEntity; //导入依赖的package包/类
@Override
public Project updateRelease(String projectName, List<ReleaseUpdate> releaseUpdates) {
	RequestEntity<List<ReleaseUpdate>> request = RequestEntity
			.put(URI.create(this.baseUrl +"/project_metadata/" + projectName + "/releases"))
			.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)
			.body(releaseUpdates);
	ResponseEntity<Project> entity = this.restTemplate
			.exchange(request, Project.class);
	Project project = entity.getBody();
	log.info("Response from Sagan\n\n[{}] \n with body [{}]", entity, project);
	return project;
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-release-tools,代码行数:13,代码来源:RestTemplateSaganClient.java

示例15: delete

import org.springframework.http.RequestEntity; //导入依赖的package包/类
public void delete(T taskId) {
    RequestEntity<Object> request = 
            new RequestEntity<>(HttpMethod.DELETE, taskUrl(taskId));
    ResponseEntity<Object> response = 
            httpClient.exchange(request, Object.class);
    assert204(response);
}
 
开发者ID:openmicroscopy,项目名称:omero-ms-queue,代码行数:8,代码来源:TaskFileStoreClient.java


注:本文中的org.springframework.http.RequestEntity类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。