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