本文整理汇总了Java中org.springframework.http.HttpEntity类的典型用法代码示例。如果您正苦于以下问题:Java HttpEntity类的具体用法?Java HttpEntity怎么用?Java HttpEntity使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpEntity类属于org.springframework.http包,在下文中一共展示了HttpEntity类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: should_put_return_406_when_assigned_to_deleted_case
import org.springframework.http.HttpEntity; //导入依赖的package包/类
@Test
public void should_put_return_406_when_assigned_to_deleted_case() throws Exception {
// given
ResponseEntity<Void> postResponse = getCreateTreatmentResponse();
URI location = postResponse.getHeaders().getLocation();
String id = RestHelper.extractIdStringFromURI(location);
Treatment savedTreatment = treatmentRepository.findOne(Long.parseLong(id));
theCase.setId(104243L);
savedTreatment.setRelevantCase(theCase);
// when
ResponseEntity<Void> putResponse = testRestTemplate
.withBasicAuth("1", "1")
.exchange("/v1/treatments/" + id,
HttpMethod.PUT,
new HttpEntity<>(savedTreatment),
Void.class);
// then
assertThat(putResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_ACCEPTABLE);
}
示例2: saveResultForClass
import org.springframework.http.HttpEntity; //导入依赖的package包/类
private String saveResultForClass(String sourcedId) {
Map<String, String> resultMetadata = Collections.singletonMap(Vocabulary.TENANT, TestData.TENANT_1);
Result result =
new Result.Builder()
.withResultstatus("Grade B")
.withScore(70.0)
.withComment("not bad")
.withMetadata(resultMetadata)
.withSourcedId(TestData.RESULT_SOURCED_ID)
.withDate(LocalDateTime.now())
.withDateLastModified(LocalDateTime.now())
.withStatus(Status.active)
.withLineitem(new Link.Builder().withSourcedId(TestData.LINEITEM_SOURCED_ID).build())
.withStudent(new Link.Builder().withSourcedId(TestData.USER_SOURCED_ID).build())
.build();
HttpHeaders headers1 = getHeaders();
HttpEntity<Object> entity = new HttpEntity<Object>(result, headers1);
ResponseEntity<Result> responseEntity =
restTemplate.exchange(String.format("/api/classes/%s/results",sourcedId), HttpMethod.POST, entity, Result.class);
Result responseResult = responseEntity.getBody();
assertTrue(responseEntity.getStatusCode().is2xxSuccessful());
assertEquals(new Double(70.0), responseResult.getScore());
return responseEntity.getBody().getSourcedId();
}
示例3: createRequestEntity
import org.springframework.http.HttpEntity; //导入依赖的package包/类
/**
* Gets the HTTP request entity encapsulating the headers and body of the HTTP message. The body
* of the HTTP request message will consist of an URL encoded application form (a mapping of
* key-value pairs) for POST/PUT HTTP requests.
* <p/>
*
* @return an HttpEntity with the headers and body for the HTTP request message.
* @see #getParameters()
* @see org.springframework.http.HttpEntity
* @see org.springframework.http.HttpHeaders
*/
public HttpEntity<?> createRequestEntity() {
if (isPost() || isPut()) {
// NOTE HTTP request parameters take precedence over HTTP message body content/media
if (!getParameters().isEmpty()) {
getHeaders().setContentType(determineContentType(MediaType.APPLICATION_FORM_URLENCODED));
return new HttpEntity<MultiValueMap<String, Object>>(getParameters(), getHeaders());
} else {
// NOTE the HTTP "Content-Type" header will be determined and set by the appropriate
// HttpMessageConverter
// based on the Class type of the "content".
return new HttpEntity<Object>(getContent(), getHeaders());
}
} else {
return new HttpEntity<Object>(getHeaders());
}
}
示例4: detectMeaningLanguageSpecific
import org.springframework.http.HttpEntity; //导入依赖的package包/类
@CrossOrigin
@RequestMapping(value = "/detectMeaningLanguageSpecific", method = RequestMethod.GET)
HttpEntity<Object> detectMeaningLanguageSpecific(@RequestParam("inputAsJson") String inputAsJson) {
try {
Logger.getAnonymousLogger().log(Level.INFO, "Invoke: detectMeaningLanguageSpecific: " + inputAsJson);
Gson gson = new Gson();
InputParameterdetectMeaningLanguageSpecific inputParameterdetectMeaningLanguageSpecific = gson
.fromJson(inputAsJson, InputParameterdetectMeaningLanguageSpecific.class);
List<Entity> concepts = sparqlDerivation.detectPossibleConceptsLanguageSpecific(
inputParameterdetectMeaningLanguageSpecific.getKeyword(),
inputParameterdetectMeaningLanguageSpecific.getLanguage());
MeaningResult meaningResult = new MeaningResult();
meaningResult.setConceptOverview(concepts);
meaningResult.setSearchTyp("ExplorativeSearch");
Gson output = new Gson();
String result = "";
result = output.toJson(meaningResult);
return new ResponseEntity<Object>(result, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<Object>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
示例5: ableToUploadFileFromConsumer
import org.springframework.http.HttpEntity; //导入依赖的package包/类
@Test
public void ableToUploadFileFromConsumer() throws IOException {
String file1Content = "hello world";
String file2Content = "bonjour";
String username = "mike";
Map<String, Object> map = new HashMap<>();
map.put("file1", new FileSystemResource(newFile(file1Content).getAbsolutePath()));
map.put("someFile", new FileSystemResource(newFile(file2Content).getAbsolutePath()));
map.put("name", username);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
String result = RestTemplateBuilder.create().postForObject(
"cse://springmvc-tests/codeFirstSpringmvc/upload",
new HttpEntity<>(map, headers),
String.class);
assertThat(result, is(file1Content + file2Content + username));
}
示例6: confirmEmail
import org.springframework.http.HttpEntity; //导入依赖的package包/类
/**
* This method activates the e-mail change using a token
* @param token E-mail change activation token
* @param uriComponentsBuilder {@link UriComponentsBuilder}
* @return The ModelAndView for sign in
*/
@PreAuthorize("permitAll()")
@GetMapping(value = "changeEmail/thanks")
public
ModelAndView confirmEmail(
@RequestParam final String token,
final UriComponentsBuilder uriComponentsBuilder
) {
SSLContextHelper.disable();
final RestTemplate restTemplate = new RestTemplate();
final HttpEntity<Object> entity = new HttpEntity<>(new HttpHeaders());
final UriComponents uriComponents
= uriComponentsBuilder.path("/api/v1.0/settings/changeEmail/token/{token}").buildAndExpand(token);
ResponseEntity<Void> response;
try {
response = restTemplate
.exchange(uriComponents.toUri(),
HttpMethod.PUT,
entity,
Void.class);
} catch (HttpClientErrorException e) /* IF 404 */ {
return new ModelAndView("tokenNotFound");
}
/* IF 200 */
return new ModelAndView("redirect:/signIn");
}
示例7: getComments
import org.springframework.http.HttpEntity; //导入依赖的package包/类
@HystrixCommand(fallbackMethod = "defaultComments")
public List<Comment> getComments(Image image, String sessionId) {
ResponseEntity<List<Comment>> results = restTemplate.exchange(
"http://COMMENTS/comments/{imageId}",
HttpMethod.GET,
new HttpEntity<>(new HttpHeaders() {{
String credentials = imagesConfiguration.getCommentsUser() + ":" +
imagesConfiguration.getCommentsPassword();
String token = new String(Base64Utils.encode(credentials.getBytes()));
set(AUTHORIZATION, "Basic " + token);
set("SESSION", sessionId);
}}),
new ParameterizedTypeReference<List<Comment>>() {},
image.getId());
return results.getBody();
}
示例8: build
import org.springframework.http.HttpEntity; //导入依赖的package包/类
public Client build() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
//prepare ROPC request
MultiValueMap<String, String> params = new LinkedMultiValueMap();
params.add(CLIENT_ID_PARAM, clientId);
params.add(CLIENT_SECRET_PARAM, clientSecret);
params.add(GRANT_TYPE_PARAM, "password");
params.add(USERNAME_PARAM, username);
params.add(PASSWORD_PARAM, password);
RestTemplate template = new RestTemplate();
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity(params, headers);
String tokenUrl = String.format("%s/oauth2/v1/token", baseUrl);
//obtain access token and return client instance
Client client = template
.exchange(tokenUrl, HttpMethod.POST, entity, Client.class)
.getBody();
client.init(baseUrl);
return client;
}
示例9: thisWeek
import org.springframework.http.HttpEntity; //导入依赖的package包/类
@Test
public void thisWeek() throws CalendarReadException {
//given
final PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
speech.setText("<event-listing>");
List<Event> events = new ArrayList<>();
doReturn(events).when(toTestQuery.calendarService).getEvents(any(), any());
doReturn(speech).when(toTestQuery.speechService).readEvents(any(), anyString(), anyList());
//when
HttpEntity<String> request = buildRequest("EventQueryThisWeek");
final SpeechletResponseEnvelope response = perform(request);
//then
verify(toTestQuery.speechService, times(1)).readEvents(
eq(Locale.GERMANY), eq(Moment.THIS_WEEK.getName(Locale.GERMANY)), anyList());
assertNull(response.getResponse().getCard());
assertTrue(response.getResponse().getOutputSpeech() instanceof PlainTextOutputSpeech);
assertEquals(
speech.getText(),
((PlainTextOutputSpeech)response.getResponse().getOutputSpeech()).getText());
}
示例10: ableToPostWithHeaderWithIdentifier
import org.springframework.http.HttpEntity; //导入依赖的package包/类
@Test
public void ableToPostWithHeaderWithIdentifier() {
Person person = new Person();
person.setName("person name");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(APPLICATION_JSON);
headers.add("prefix-test", "prefix prefix");
HttpEntity<Person> requestEntity = new HttpEntity<>(person, headers);
for (String url : urls) {
ResponseEntity<String> responseEntity = restTemplate
.postForEntity(url + "saysomething1", requestEntity, String.class);
assertEquals("prefix prefix person name", jsonBodyOf(responseEntity, String.class));
}
}
示例11: verifyGenerate
import org.springframework.http.HttpEntity; //导入依赖的package包/类
void verifyGenerate(ResponseEntity<CredentialDetails<T>> expectedResponse) {
ParametersRequest<P> request = getGenerateRequest();
when(restTemplate.exchange(eq(BASE_URL_PATH), eq(POST),
eq(new HttpEntity<>(request)), isA(ParameterizedTypeReference.class)))
.thenReturn(expectedResponse);
if (!expectedResponse.getStatusCode().equals(HttpStatus.OK)) {
try {
credHubTemplate.generate(request);
fail("Exception should have been thrown");
}
catch (CredHubException e) {
assertThat(e.getMessage(), containsString(expectedResponse.getStatusCode().toString()));
}
}
else {
CredentialDetails<T> response = credHubTemplate.generate(request);
assertDetailsResponseContainsExpectedCredential(expectedResponse, response);
}
}
示例12: getPropertyValuesDiscretised
import org.springframework.http.HttpEntity; //导入依赖的package包/类
/**
* Returns from a given concept the data properties and obejctproperties and
* to each objecproperty a concept in the case the step range is greater 1
*
* @param concept
* @param step
* range
* @param
* @return
*/
@CrossOrigin
@RequestMapping(value = "/getPropertyValuesDiscretised", method = RequestMethod.GET)
HttpEntity<Object> getPropertyValuesDiscretised(@RequestParam("inputAsJson") String inputAsJson) {
try {
Logger.getAnonymousLogger().log(Level.INFO, "Invoke: getPropertyValuesDiscretised: " + inputAsJson);
Gson gson = new Gson();
InputParameterForgetPropertyValuesDiscretised paramterForGetLogicalView = gson.fromJson(inputAsJson,
InputParameterForgetPropertyValuesDiscretised.class);
Map<String, List<Group>> mapOfPropertyGroups = sparqlDerivation.generateGroup(
paramterForGetLogicalView.getAmountOfGroups(), paramterForGetLogicalView.getConcept(),
paramterForGetLogicalView.getProperty());
String result = "";
result = gson.toJson(mapOfPropertyGroups);
return new ResponseEntity<Object>(result, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<Object>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
示例13: should_put_return_406__when_assigned_to_not_persisted_case
import org.springframework.http.HttpEntity; //导入依赖的package包/类
@Test
public void should_put_return_406__when_assigned_to_not_persisted_case() throws Exception {
// given
ResponseEntity<Void> postResponse = getCreateTreatmentResponse();
URI location = postResponse.getHeaders().getLocation();
String id = RestHelper.extractIdStringFromURI(location);
Treatment savedTreatment = treatmentRepository.findOne(Long.parseLong(id));
theCase.setId(null);
savedTreatment.setRelevantCase(theCase);
// when
ResponseEntity<Void> putResponse = testRestTemplate
.withBasicAuth("1", "1")
.exchange("/v1/treatments/" + id,
HttpMethod.PUT,
new HttpEntity<>(savedTreatment),
Void.class);
// then
assertThat(putResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_ACCEPTABLE);
}
示例14: doPost
import org.springframework.http.HttpEntity; //导入依赖的package包/类
@Override
// A. It must be a POST request.
protected void doPost(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) throws ServletException, IOException {
byte[] serializedSpeechletRequest = IOUtils.toByteArray(httpRequest.getInputStream());
try {
if (this.checkAmazonSignature) {
// B. It must come from the Amazon Alexa cloud.
SpeechletRequestSignatureVerifier.checkRequestSignature(serializedSpeechletRequest,
httpRequest.getHeader(Sdk.SIGNATURE_REQUEST_HEADER),
httpRequest.getHeader(Sdk.SIGNATURE_CERTIFICATE_CHAIN_URL_REQUEST_HEADER));
}
final SpeechletRequestEnvelope<?> requestEnvelope = SpeechletRequestEnvelope.fromJson(serializedSpeechletRequest);
for (SpeechletRequestEnvelopeVerifier verifier : this.requestEnvelopeVerifiers) {
if (!verifier.verify(requestEnvelope)) {
throw new SpeechletRequestHandlerException(this.createExceptionMessage(verifier, requestEnvelope));
}
}
HttpEntity<byte[]> requestEntity = new HttpEntity<>(serializedSpeechletRequest);
ResponseEntity<SpeechletResponseEnvelope> speechletResponse = this.restTemplate.postForEntity(
this.endpoint, requestEntity, SpeechletResponseEnvelope.class);
if (speechletResponse.getStatusCode().is2xxSuccessful() && speechletResponse.hasBody()) {
byte[] outputBytes = speechletResponse.getBody().toJsonBytes();
httpResponse.setContentType("application/json");
httpResponse.setStatus(speechletResponse.getStatusCodeValue());
httpResponse.setContentLength(outputBytes.length);
httpResponse.getOutputStream().write(outputBytes);
} else {
// Should never happen, cause all edge cases are already covered by actual exceptions thrown.
httpResponse.sendError(speechletResponse.getStatusCodeValue(), "Unexpected error in proxy");
}
} catch (Exception e) {
int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
if (BAD_REQUEST_EXCEPTION_TYPES.contains(e.getClass())) {
statusCode = HttpServletResponse.SC_BAD_REQUEST;
}
this.log.error("Exception occurred in doPost, returning status code {}", statusCode, e);
httpResponse.sendError(statusCode, e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
示例15: verifyGetByNameWithHistory
import org.springframework.http.HttpEntity; //导入依赖的package包/类
@SuppressWarnings("deprecation")
void verifyGetByNameWithHistory(ResponseEntity<CredentialDetailsData<T>> expectedResponse) {
when(restTemplate.exchange(eq(NAME_URL_QUERY), eq(GET), isNull(HttpEntity.class),
isA(ParameterizedTypeReference.class), eq(NAME.getName())))
.thenReturn(expectedResponse);
if (!expectedResponse.getStatusCode().equals(OK)) {
try {
credHubTemplate.getByNameWithHistory(NAME, String.class);
fail("Exception should have been thrown");
}
catch (CredHubException e) {
assertThat(e.getMessage(),
containsString(expectedResponse.getStatusCode().toString()));
}
}
else {
List<CredentialDetails<T>> response = credHubTemplate.getByNameWithHistory(NAME, getType());
assertDataResponseContainsExpectedCredentials(expectedResponse, response);
}
}