下面列出了org.springframework.http.converter.FormHttpMessageConverter#org.springframework.util.MultiValueMap 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
Channel openIm(User user) throws SlackClientException {
Preconditions.checkNotNull(user.getId());
MultiValueMap<String, Object> payload = getBasePayloadMapWithAuthToken();
payload.add("user", user.getId());
payload.add("return_im", "true");
HttpEntity<MultiValueMap<String, Object>> httpEntity = getHttpEntityForPayload(payload);
ImOpenResponse imOpenResponse = restTemplate.postForObject(getUrl(API_IM_OPEN), httpEntity, ImOpenResponse.class);
if (!imOpenResponse.getOk()) {
String msg = MessageFormat.format("Cannot open instant message: {0}", imOpenResponse.getError());
logger.debug(msg);
throw new SlackClientException(msg);
}
return imOpenResponse.getChannel();
}
@Test
public void execDifferentCall() {
String requestId1 = "execDiffrentCall_:"+UUID.randomUUID();
String requestId2 = "execDiffrentCall_:"+UUID.randomUUID();
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add(Constants.REQ_IDEM_ID, requestId1);
headers.add("Content-Type", "application/json");
HttpEntity requests = new HttpEntity(headers);
ResponseEntity<String> response = restTemplate.exchange(REQ_URL, HttpMethod.GET, requests,
String.class);
String reponse1 = response.getBody();
MultiValueMap<String, String> headers2 = new LinkedMultiValueMap<String, String>();
headers.add(Constants.REQ_IDEM_ID, requestId2);
headers.add("Content-Type", "application/json");
HttpEntity requests2 = new HttpEntity(headers2);
ResponseEntity<String> response2 = restTemplate.exchange(REQ_URL, HttpMethod.GET, requests2,
String.class);
String reponse2 = response2.getBody();
System.out.println(reponse1 + "\n" + reponse2);
Assert.assertNotEquals("The different result", reponse1, reponse2);
}
@Test
public void multipartFileResource() throws IOException {
String name = "file";
String disposition = "form-data; name=\"" + name + "\"; filename=\"myFile.txt\"";
StandardMultipartHttpServletRequest request = requestWithPart(name, disposition, "myBody");
MultipartFile multipartFile = request.getFile(name);
assertNotNull(multipartFile);
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add(name, multipartFile.getResource());
MockHttpOutputMessage output = new MockHttpOutputMessage();
new FormHttpMessageConverter().write(map, null, output);
assertThat(output.getBodyAsString(StandardCharsets.UTF_8), containsString(
"Content-Disposition: form-data; name=\"file\"; filename=\"myFile.txt\"\r\n" +
"Content-Type: text/plain\r\n" +
"Content-Length: 6\r\n" +
"\r\n" +
"myBody\r\n"));
}
@Test
public void givenFooService_whenFormSubmit_thenResourceIsCreated() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("id", "1");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity( fooResourceUrl+"/form", request , String.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
final String fooResponse = response.getBody();
assertThat(fooResponse, notNullValue());
assertThat(fooResponse, is("1"));
}
@Test
public void createWithConnectNativeHeaders() {
MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>();
extHeaders.add(StompHeaderAccessor.STOMP_LOGIN_HEADER, "joe");
extHeaders.add(StompHeaderAccessor.STOMP_PASSCODE_HEADER, "joe123");
StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.CONNECT, extHeaders);
assertEquals(StompCommand.CONNECT, headerAccessor.getCommand());
assertEquals(SimpMessageType.CONNECT, headerAccessor.getMessageType());
assertNotNull(headerAccessor.getHeader("stompCredentials"));
assertEquals("joe", headerAccessor.getLogin());
assertEquals("joe123", headerAccessor.getPasscode());
assertThat(headerAccessor.toString(), CoreMatchers.containsString("passcode=[PROTECTED]"));
Map<String, List<String>> output = headerAccessor.toNativeHeaderMap();
assertEquals("joe", output.get(StompHeaderAccessor.STOMP_LOGIN_HEADER).get(0));
assertEquals("PROTECTED", output.get(StompHeaderAccessor.STOMP_PASSCODE_HEADER).get(0));
}
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");
}
/**
* Encode all URI components using their specific encoding rules and return
* the result as a new {@code UriComponents} instance.
* @param encoding the encoding of the values
* @return the encoded uri components
* @throws UnsupportedEncodingException if the given encoding is not supported
*/
@Override
public HierarchicalUriComponents encode(String encoding) throws UnsupportedEncodingException {
if (this.encoded) {
return this;
}
Assert.hasLength(encoding, "Encoding must not be empty");
String schemeTo = encodeUriComponent(getScheme(), encoding, Type.SCHEME);
String userInfoTo = encodeUriComponent(this.userInfo, encoding, Type.USER_INFO);
String hostTo = encodeUriComponent(this.host, encoding, getHostType());
PathComponent pathTo = this.path.encode(encoding);
MultiValueMap<String, String> paramsTo = encodeQueryParams(encoding);
String fragmentTo = encodeUriComponent(getFragment(), encoding, Type.FRAGMENT);
return new HierarchicalUriComponents(schemeTo, userInfoTo, hostTo, this.port,
pathTo, paramsTo, fragmentTo, true, false);
}
@GetMapping(path = Mapping.URL_WORKBASKET)
@Transactional(readOnly = true, rollbackFor = Exception.class)
public ResponseEntity<TaskanaPagedModel<WorkbasketSummaryRepresentationModel>> getWorkbaskets(
@RequestParam MultiValueMap<String, String> params) throws InvalidArgumentException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Entry to getWorkbaskets(params= {})", params);
}
WorkbasketQuery query = workbasketService.createWorkbasketQuery();
query = applySortingParams(query, params);
applyFilterParams(query, params);
PageMetadata pageMetadata = getPageMetadata(params, query);
List<WorkbasketSummary> workbasketSummaries = getQueryList(query, pageMetadata);
TaskanaPagedModel<WorkbasketSummaryRepresentationModel> pagedModels =
workbasketSummaryRepresentationModelAssembler.toPageModel(
workbasketSummaries, pageMetadata);
ResponseEntity<TaskanaPagedModel<WorkbasketSummaryRepresentationModel>> response =
ResponseEntity.ok(pagedModels);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Exit from getWorkbaskets(), returning {}", response);
}
return response;
}
@Test
public void handshakeHandlerAndInterceptorWithAllowedOrigins() {
WebMvcStompWebSocketEndpointRegistration registration =
new WebMvcStompWebSocketEndpointRegistration(new String[] {"/foo"}, this.handler, this.scheduler);
DefaultHandshakeHandler handshakeHandler = new DefaultHandshakeHandler();
HttpSessionHandshakeInterceptor interceptor = new HttpSessionHandshakeInterceptor();
String origin = "https://mydomain.com";
registration.setHandshakeHandler(handshakeHandler).addInterceptors(interceptor).setAllowedOrigins(origin);
MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
assertEquals(1, mappings.size());
Map.Entry<HttpRequestHandler, List<String>> entry = mappings.entrySet().iterator().next();
assertEquals(Arrays.asList("/foo"), entry.getValue());
WebSocketHttpRequestHandler requestHandler = (WebSocketHttpRequestHandler) entry.getKey();
assertNotNull(requestHandler.getWebSocketHandler());
assertSame(handshakeHandler, requestHandler.getHandshakeHandler());
assertEquals(2, requestHandler.getHandshakeInterceptors().size());
assertEquals(interceptor, requestHandler.getHandshakeInterceptors().get(0));
assertEquals(OriginHandshakeInterceptor.class, requestHandler.getHandshakeInterceptors().get(1).getClass());
}
@Test
public void canRead() {
assertTrue(this.reader.canRead(
forClassWithGenerics(MultiValueMap.class, String.class, Part.class),
MediaType.MULTIPART_FORM_DATA));
assertFalse(this.reader.canRead(
forClassWithGenerics(MultiValueMap.class, String.class, Object.class),
MediaType.MULTIPART_FORM_DATA));
assertFalse(this.reader.canRead(
forClassWithGenerics(MultiValueMap.class, String.class, String.class),
MediaType.MULTIPART_FORM_DATA));
assertFalse(this.reader.canRead(
forClassWithGenerics(Map.class, String.class, String.class),
MediaType.MULTIPART_FORM_DATA));
assertFalse(this.reader.canRead(
forClassWithGenerics(MultiValueMap.class, String.class, Part.class),
MediaType.APPLICATION_FORM_URLENCODED));
}
/**
* Get the annotation attributes of <strong>all</strong> annotations of
* the specified {@code annotationName} in the annotation hierarchy above
* the supplied {@link AnnotatedElement} and store the results in a
* {@link MultiValueMap}.
* <p>Note: in contrast to {@link #getMergedAnnotationAttributes(AnnotatedElement, String)},
* this method does <em>not</em> support attribute overrides.
* <p>This method follows <em>get semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element
* @param annotationName the fully qualified class name of the annotation type to find
* @param classValuesAsString whether to convert Class references into Strings or to
* preserve them as Class references
* @param nestedAnnotationsAsMap whether to convert nested Annotation instances into
* {@code AnnotationAttributes} maps or to preserve them as Annotation instances
* @return a {@link MultiValueMap} keyed by attribute name, containing the annotation
* attributes from all annotations found, or {@code null} if not found
*/
public static MultiValueMap<String, Object> getAllAnnotationAttributes(AnnotatedElement element,
String annotationName, final boolean classValuesAsString, final boolean nestedAnnotationsAsMap) {
final MultiValueMap<String, Object> attributesMap = new LinkedMultiValueMap<String, Object>();
searchWithGetSemantics(element, null, annotationName, new SimpleAnnotationProcessor<Object>() {
@Override
public Object process(AnnotatedElement annotatedElement, Annotation annotation, int metaDepth) {
AnnotationAttributes annotationAttributes = AnnotationUtils.getAnnotationAttributes(
annotation, classValuesAsString, nestedAnnotationsAsMap);
for (Map.Entry<String, Object> entry : annotationAttributes.entrySet()) {
attributesMap.add(entry.getKey(), entry.getValue());
}
return CONTINUE;
}
});
return (!attributesMap.isEmpty() ? attributesMap : null);
}
/**
* 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());
}
}
@Override
protected void doFilterInternal(final HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
if (("PUT".equals(request.getMethod()) || "PATCH".equals(request.getMethod())) && isFormContentType(request)) {
HttpInputMessage inputMessage = new ServletServerHttpRequest(request) {
@Override
public InputStream getBody() throws IOException {
return request.getInputStream();
}
};
MultiValueMap<String, String> formParameters = formConverter.read(null, inputMessage);
HttpServletRequest wrapper = new HttpPutFormContentRequestWrapper(request, formParameters);
filterChain.doFilter(wrapper, response);
}
else {
filterChain.doFilter(request, response);
}
}
private boolean validateBeforeFinish(HttpServletRequest request, String sessionMapID) {
SessionMap<String, Object> sessionMap = getSessionMap(request);
Long sessionId = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID);
HttpSession ss = SessionManager.getSession();
UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
Long userID = user.getUserID().longValue();
int numberCompletedTasks = taskListService.getNumTasksCompletedByUser(sessionId, userID);
int minimumNumberTasks = taskListService.getTaskListBySessionId(sessionId).getMinimumNumberTasks();
// if current user view less than reqired view count number, then just return error message.
if ((minimumNumberTasks - numberCompletedTasks) > 0) {
MultiValueMap<String, String> errorMap = new LinkedMultiValueMap<>();
errorMap.add("GLOBAL", messageService.getMessage("lable.learning.minimum.view.number"));
request.setAttribute("errorMap", errorMap);
return false;
}
return true;
}
@Override
public OAuth2Authentication loadAuthentication(final String accessToken)
throws AuthenticationException, InvalidTokenException {
final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add(tokenName, accessToken);
final HttpHeaders headers = new HttpHeaders();
String req = "";
try {
req = checkTokenEndpointUrl + "?access_token=" + URLEncoder.encode(accessToken, "UTF-8");
} catch (final UnsupportedEncodingException e) {
logger.error("Unsupported encoding", e);
}
final Map<String, Object> map = getForMap(req, formData, headers);
if (map.containsKey("error")) {
logger.debug("check_token returned error: " + map.get("error"));
throw new InvalidTokenException(accessToken);
}
return tokenConverter.extractAuthentication(map);
}
@Test
public void ableToPostDate() throws Exception {
ZonedDateTime date = ZonedDateTime.now().truncatedTo(SECONDS);
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("date", RestObjectMapperFactory.getRestObjectMapper().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())));
ListenableFuture<ResponseEntity<Date>> listenableFuture = asyncRestTemplate
.postForEntity(codeFirstUrl + "addDate?seconds={seconds}",
new HttpEntity<>(body, headers),
Date.class,
seconds);
ResponseEntity<Date> dateResponseEntity = listenableFuture.get();
assertThat(dateResponseEntity.getBody(), is(Date.from(date.plusSeconds(seconds).toInstant())));
}
@Test
public void retrieveToken_setsUsername() throws OAuth2ServiceException {
cut.retrieveAccessTokenViaPasswordGrant(tokenEndpoint, clientCredentials,
username, password, null, null);
ArgumentCaptor<HttpEntity<MultiValueMap<String, String>>> requestEntityCaptor = captureRequestEntity();
assertThat(valueOfParameter(USERNAME, requestEntityCaptor)).isEqualTo(username);
}
/**
* Expose URI template variables, matrix variables, and producible media types in the request.
* @see HandlerMapping#URI_TEMPLATE_VARIABLES_ATTRIBUTE
* @see HandlerMapping#MATRIX_VARIABLES_ATTRIBUTE
* @see HandlerMapping#PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE
*/
@Override
protected void handleMatch(RequestMappingInfo info, HandlerMethod handlerMethod,
ServerWebExchange exchange) {
super.handleMatch(info, handlerMethod, exchange);
PathContainer lookupPath = exchange.getRequest().getPath().pathWithinApplication();
PathPattern bestPattern;
Map<String, String> uriVariables;
Map<String, MultiValueMap<String, String>> matrixVariables;
Set<PathPattern> patterns = info.getPatternsCondition().getPatterns();
if (patterns.isEmpty()) {
bestPattern = getPathPatternParser().parse(lookupPath.value());
uriVariables = Collections.emptyMap();
matrixVariables = Collections.emptyMap();
}
else {
bestPattern = patterns.iterator().next();
PathPattern.PathMatchInfo result = bestPattern.matchAndExtract(lookupPath);
Assert.notNull(result, () ->
"Expected bestPattern: " + bestPattern + " to match lookupPath " + lookupPath);
uriVariables = result.getUriVariables();
matrixVariables = result.getMatrixVariables();
}
exchange.getAttributes().put(BEST_MATCHING_HANDLER_ATTRIBUTE, handlerMethod);
exchange.getAttributes().put(BEST_MATCHING_PATTERN_ATTRIBUTE, bestPattern);
exchange.getAttributes().put(URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriVariables);
exchange.getAttributes().put(MATRIX_VARIABLES_ATTRIBUTE, matrixVariables);
if (!info.getProducesCondition().getProducibleMediaTypes().isEmpty()) {
Set<MediaType> mediaTypes = info.getProducesCondition().getProducibleMediaTypes();
exchange.getAttributes().put(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, mediaTypes);
}
}
@Test // SPR-12283
public void disableCorsWithSockJsService() {
WebMvcStompWebSocketEndpointRegistration registration =
new WebMvcStompWebSocketEndpointRegistration(new String[] {"/foo"}, this.handler, this.scheduler);
registration.withSockJS().setSupressCors(true);
MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
assertEquals(1, mappings.size());
SockJsHttpRequestHandler requestHandler = (SockJsHttpRequestHandler)mappings.entrySet().iterator().next().getKey();
assertNotNull(requestHandler.getSockJsService());
DefaultSockJsService sockJsService = (DefaultSockJsService)requestHandler.getSockJsService();
assertTrue(sockJsService.shouldSuppressCors());
}
/**
* {@code GET /audits} : get a page of {@link AuditEvent} between the {@code fromDate} and {@code toDate}.
*
* @param fromDate the start of the time period of {@link AuditEvent} to get.
* @param toDate the end of the time period of {@link AuditEvent} to get.
* @param pageable the pagination information.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of {@link AuditEvent} in body.
*/
@GetMapping(params = {"fromDate", "toDate"})
public ResponseEntity<List<AuditEvent>> getByDates(
@RequestParam(value = "fromDate") LocalDate fromDate,
@RequestParam(value = "toDate") LocalDate toDate,
@RequestParam MultiValueMap<String, String> queryParams, UriComponentsBuilder uriBuilder,
Pageable pageable) {
Page<AuditEvent> page = auditEventService.findByDates(
fromDate.atStartOfDay(ZoneId.systemDefault()).toInstant(),
toDate.atStartOfDay(ZoneId.systemDefault()).plusDays(1).toInstant(),
pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(uriBuilder.queryParams(queryParams), page);
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
private URI getUrlToUse() {
MultiValueMap<String, String> params =
this.queryParamsBuilder.buildAndExpand().encode().getQueryParams();
if (!params.isEmpty()) {
return UriComponentsBuilder.fromUri(this.url).queryParams(params).build(true).toUri();
}
return this.url;
}
@Override
public void applyToParams(MultiValueMap<String, String> queryParams, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams) {
if (username == null && password == null) {
return;
}
String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
headerParams.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString(str.getBytes(StandardCharsets.UTF_8)));
}
/**
* 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 (required)
* @return ResponseEntity<Void>
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<Void> addPetWithHttpInfo(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 = apiClient.expandPath("/pet", 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 = {
"application/json", "application/xml"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "petstore_auth" };
ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
@Test
public void getAllAnnotationAttributesOnJavaxType() {
MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(
ParametersAreNonnullByDefault.class, Nonnull.class.getName());
assertNotNull("Annotation attributes map for @Nonnull on NonNullApi", attributes);
assertEquals("value for NonNullApi", asList(When.ALWAYS), attributes.get("when"));
}
private static <K,V> void copy(MultiValueMap<K,V> src, MultiValueMap<K,V> dst) {
if (!src.isEmpty()) {
src.entrySet().stream()
.filter(entry -> !dst.containsKey(entry.getKey()))
.forEach(entry -> dst.put(entry.getKey(), entry.getValue()));
}
}
@Override
public Credential fromRequestBody(@NotNull final MultiValueMap<String, String> requestBody) {
final String username = requestBody.getFirst("username");
final String password = requestBody.getFirst("password");
if(username == null || password == null) {
throw new BadRequestException("Invalid payload. 'username' and 'password' form fields are required.");
}
return new UsernamePasswordCredential(requestBody.getFirst("username"), requestBody.getFirst("password"));
}
@Override
protected MultiValueMap<String, HttpCookie> initCookies() {
MultiValueMap<String, HttpCookie> cookies = new LinkedMultiValueMap<>();
for (String name : this.exchange.getRequestCookies().keySet()) {
Cookie cookie = this.exchange.getRequestCookies().get(name);
HttpCookie httpCookie = new HttpCookie(name, cookie.getValue());
cookies.add(name, httpCookie);
}
return cookies;
}
@Override
public AccessGrant refreshAccess(String refreshToken, MultiValueMap<String, String> additionalParameters) {
StringBuilder refreshTokenUrl = new StringBuilder(FebsConstant.WEIXIN_REFRESH_TOKEN_URL);
refreshTokenUrl.append("?appid=").append(clientId);
refreshTokenUrl.append("&grant_type=refresh_token");
refreshTokenUrl.append("&refresh_token=").append(refreshToken);
return getAccessToken(refreshTokenUrl);
}
@Before
public void setup() throws Exception {
resolver = new RequestHeaderMapMethodArgumentResolver();
Method method = getClass().getMethod("params", Map.class, MultiValueMap.class, HttpHeaders.class, Map.class);
paramMap = new SynthesizingMethodParameter(method, 0);
paramMultiValueMap = new SynthesizingMethodParameter(method, 1);
paramHttpHeaders = new SynthesizingMethodParameter(method, 2);
paramUnsupported = new SynthesizingMethodParameter(method, 3);
request = new MockHttpServletRequest();
webRequest = new ServletWebRequest(request, new MockHttpServletResponse());
}
@GetMapping("/multiValue")
public ResponseEntity<String> multiValue(@RequestHeader MultiValueMap<String, String> headers) {
headers.forEach((key, value) -> {
LOG.info(String.format("Header '%s' = %s", key, value.stream().collect(Collectors.joining("|"))));
});
return new ResponseEntity<String>(String.format("Listed %d headers", headers.size()), HttpStatus.OK);
}