本文整理汇总了Java中org.springframework.util.MultiValueMap类的典型用法代码示例。如果您正苦于以下问题:Java MultiValueMap类的具体用法?Java MultiValueMap怎么用?Java MultiValueMap使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MultiValueMap类属于org.springframework.util包,在下文中一共展示了MultiValueMap类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: send
import org.springframework.util.MultiValueMap; //导入依赖的package包/类
private void send(String subject, String to, String toEmail, String body) {
final String url = "https://api.mailgun.net/v3/" +
env.getProperty("mailgun.domain") + "/messages";
final MultiValueMap<String, String> args = new LinkedMultiValueMap<>();
args.put("subject", singletonList(subject));
args.put("from", singletonList(env.getProperty("service.email.sitename") +
" <" + env.getProperty("service.email.sender") + ">"));
args.put("to", singletonList(to + " <" + toEmail + ">"));
args.put("html", singletonList(body));
final ResponseEntity<MailGunResponse> response =
mailgun.postForEntity(url, args, MailGunResponse.class);
if (!response.getStatusCode().is2xxSuccessful()) {
throw new RuntimeException(
"Error delivering mail. Message: " +
response.getBody().getMessage()
);
}
}
示例2: getAnswer
import org.springframework.util.MultiValueMap; //导入依赖的package包/类
public static String getAnswer(RestTemplate restTemplate, String question) {
String url = "http://www.tuling123.com/openapi/api";
HttpHeaders headers = new HttpHeaders();
headers.add("Ocp-Apim-Subscription-Key", "3f5a37d9698744f3b40c89e2f0c94fb1");
headers.add("Content-Type", "application/x-www-form-urlencoded");
MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<>();
bodyMap.add("key", "e2e33efb4efb4e5794b48a18578384ee");
bodyMap.add("info", question);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(bodyMap, headers);
String result = restTemplate.postForObject(url, requestEntity, String.class);
return JsonPath.read(result, "$.text");
}
示例3: handleReturnValue
import org.springframework.util.MultiValueMap; //导入依赖的package包/类
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
if (returnValue == null) {
mavContainer.setRequestHandled(true);
return;
}
final AsyncResponseEntity<?> asyncResponseEntity = AsyncResponseEntity.class.cast(returnValue);
Observable<?> observable = asyncResponseEntity.getObservable();
Single<?> single = asyncResponseEntity.getSingle();
MultiValueMap<String, String> headers = asyncResponseEntity.getHeaders();
HttpStatus status = asyncResponseEntity.getStatus();
if(observable != null)
WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(new ObservableDeferredResult<>(observable, headers, status), mavContainer);
else if(single != null)
WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(new SingleDeferredResult<>(single, headers, status), mavContainer);
}
开发者ID:quebic-source,项目名称:microservices-sample-project,代码行数:22,代码来源:AsyncResponseEntityReturnHandler.java
示例4: createRequestEntity
import org.springframework.util.MultiValueMap; //导入依赖的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());
}
}
示例5: findConnectionsToUsers
import org.springframework.util.MultiValueMap; //导入依赖的package包/类
@Test
@SuppressWarnings("unchecked")
public void findConnectionsToUsers() {
connectionFactoryRegistry.addConnectionFactory(new TestTwitterConnectionFactory());
insertTwitterConnection();
insertFacebookConnection();
insertFacebookConnection2();
MultiValueMap<String, String> providerUsers = new LinkedMultiValueMap<>();
providerUsers.add("facebook", "10");
providerUsers.add("facebook", "9");
providerUsers.add("twitter", "1");
MultiValueMap<String, Connection<?>> connectionsForUsers = connectionRepository.findConnectionsToUsers(providerUsers);
assertEquals(2, connectionsForUsers.size());
String providerId=connectionsForUsers.getFirst("facebook").getKey().getProviderUserId();
assertTrue("10".equals(providerId) || "9".equals(providerId) );
assertFacebookConnection((Connection<TestFacebookApi>) connectionRepository.getConnection(new ConnectionKey("facebook", "9")));
assertTwitterConnection((Connection<TestTwitterApi>) connectionsForUsers.getFirst("twitter"));
}
示例6: ableToUploadFileWithoutAnnotation
import org.springframework.util.MultiValueMap; //导入依赖的package包/类
@Test
public void ableToUploadFileWithoutAnnotation() throws IOException {
String file1Content = "hello world";
String file2Content = "bonjour";
String username = "mike";
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file1", new FileSystemResource(newFile(file1Content).getAbsolutePath()));
map.add("file2", new FileSystemResource(newFile(file2Content).getAbsolutePath()));
map.add("name", username);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
String result = restTemplate.postForObject(
codeFirstUrl + "uploadWithoutAnnotation",
new HttpEntity<>(map, headers),
String.class);
assertThat(result, is(file1Content + file2Content + username));
}
示例7: buildResponseEntity
import org.springframework.util.MultiValueMap; //导入依赖的package包/类
private HttpEntity<MultiValueMap<String, String>> buildResponseEntity(
Submission submission, HttpHeaders headers) {
logger.debug("Building response entity");
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
try {
map.add("test_output", new ObjectMapper().writeValueAsString(
submission.getTestOutput()));
} catch (JsonProcessingException ex) {
logger.debug("POJO deserialization failed");
}
map.add("stdout", submission.getStdout());
map.add("stderr", submission.getStderr());
map.add("validations", submission.getValidations());
map.add("vm_log", submission.getVmLog());
map.add("token", submission.getId().toString());
map.add("status", submission.getStatus().toString());
map.add("exit_code", submission.getExitCode().toString());
return new HttpEntity<>(map, headers);
}
示例8: ableToPostDate
import org.springframework.util.MultiValueMap; //导入依赖的package包/类
@Test
public void ableToPostDate() throws Exception {
ZonedDateTime date = ZonedDateTime.now().truncatedTo(SECONDS);
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("date", RestObjectMapper.INSTANCE.convertToString(Date.from(date.toInstant())));
HttpHeaders headers = new HttpHeaders();
headers.add(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE);
int seconds = 1;
Date result = restTemplate.postForObject(codeFirstUrl + "addDate?seconds={seconds}",
new HttpEntity<>(body, headers),
Date.class,
seconds);
assertThat(result, is(Date.from(date.plusSeconds(seconds).toInstant())));
}
示例9: main
import org.springframework.util.MultiValueMap; //导入依赖的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: buildSolrRequest
import org.springframework.util.MultiValueMap; //导入依赖的package包/类
@Override
protected QueryRequest buildSolrRequest(ComponentConfiguration conf, Template intent, Conversation conversation, long offset, int pageSize, MultiValueMap<String, String> queryParams) {
final ConversationMltQuery mltQuery = buildQuery(conf, intent, conversation);
if (mltQuery == null) {
return null;
}
final SolrQuery solrQuery = new SolrQuery();
solrQuery.addField("*").addField("score");
solrQuery.addFilterQuery(String.format("%s:%s", FIELD_TYPE, TYPE_MESSAGE));
solrQuery.addFilterQuery(String.format("%s:0",FIELD_MESSAGE_IDX));
solrQuery.addSort("score", SolrQuery.ORDER.desc).addSort(FIELD_VOTE, SolrQuery.ORDER.desc);
// #39 - paging
solrQuery.setStart((int) offset);
solrQuery.setRows(pageSize);
//since #46 the client field is used to filter for the current user
addClientFilter(solrQuery, conversation);
addPropertyFilters(solrQuery, conversation, conf);
return new ConversationMltRequest(solrQuery, mltQuery.getContent());
}
示例11: apiAuthorizationLoginPost
import org.springframework.util.MultiValueMap; //导入依赖的package包/类
/**
*
*
* <p><b>200</b> - Success
* @param model The model parameter
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public void apiAuthorizationLoginPost(LoginModel model) throws RestClientException {
Object postBody = model;
String path = UriComponentsBuilder.fromPath("/api/authorization/login").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 = { };
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json-patch+json", "application/json", "text/json", "application/_*+json"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
示例12: invokeAPI
import org.springframework.util.MultiValueMap; //导入依赖的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");
}
}
示例13: applyToParams
import org.springframework.util.MultiValueMap; //导入依赖的package包/类
@Override
public void applyToParams(MultiValueMap<String, String> queryParams, HttpHeaders headerParams) {
if (apiKey == null) {
return;
}
String value;
if (apiKeyPrefix != null) {
value = apiKeyPrefix + " " + apiKey;
} else {
value = apiKey;
}
if (location.equals("query")) {
queryParams.add(paramName, value);
} else if (location.equals("header")) {
headerParams.add(paramName, value);
}
}
示例14: shouldRetrieveNewStories
import org.springframework.util.MultiValueMap; //导入依赖的package包/类
@Test
public void shouldRetrieveNewStories() throws Exception{
Story story = generateStory();
Geolocation geolocation = new Geolocation();
geolocation.setLatitude(0);
geolocation.setLongitude(0);
MultiValueMap<String,String> params = new LinkedMultiValueMap<>();
params.add("latitude",String.valueOf(geolocation.getLatitude()));
params.add("longitude",String.valueOf(geolocation.getLongitude()));
when(homepageService.retrieveNewStories(anyString(),any(Geolocation.class))).thenReturn(ImmutableList.of(story));
mockMvc.perform(get("/homepage/retrieveNewStories").params(params).principal(new UserPrincipal("testUserId")))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(story.getId()));
}
示例15: testDeleteUserSocialConnection
import org.springframework.util.MultiValueMap; //导入依赖的package包/类
@Test
public void testDeleteUserSocialConnection() throws Exception {
// Setup
Connection<?> connection = createConnection("@LOGIN",
"[email protected]om",
"FIRST_NAME",
"LAST_NAME",
"IMAGE_URL",
"PROVIDER");
socialService.createSocialUser(connection, "fr");
MultiValueMap<String, Connection<?>> connectionsByProviderId = new LinkedMultiValueMap<>();
connectionsByProviderId.put("PROVIDER", null);
when(mockConnectionRepository.findAllConnections()).thenReturn(connectionsByProviderId);
// Exercise
socialService.deleteUserSocialConnection("@LOGIN");
// Verify
verify(mockConnectionRepository, times(1)).removeConnections("PROVIDER");
}