Java Code Examples for org.springframework.util.MultiValueMap#put()

The following examples show how to use org.springframework.util.MultiValueMap#put() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PreparationGetMetadata.java    From data-prep with Apache License 2.0 6 votes vote down vote up
private ResponseEntity<DataSetMetadata> getResponseEntity(HttpStatus status, HttpResponse response) {

        final MultiValueMap<String, String> headers = new HttpHeaders();
        for (Header header : response.getAllHeaders()) {
            if (HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) {
                headers.put(header.getName(), Collections.singletonList(header.getValue()));
            }
        }
        try (final InputStream content = response.getEntity().getContent();
                final InputStreamReader contentReader = new InputStreamReader(content, UTF_8)) {
            DataSetMetadata result = objectMapper.readValue(contentReader, DataSetMetadata.class);
            return new ResponseEntity<>(result, headers, status);
        } catch (IOException e) {
            throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
        }
    }
 
Example 2
Source File: FlowABCTokenExchangeController.java    From oauth2-protocol-patterns with Apache License 2.0 6 votes vote down vote up
@GetMapping
public String flowABC_TokenExchange(@RegisteredOAuth2AuthorizedClient("client-ab") OAuth2AuthorizedClient clientAB,
									OAuth2AuthenticationToken oauth2Authentication,
									HttpServletRequest request,
									Map<String, Object> model) {

	ServiceCallResponse serviceACallResponse = callService(ServicesConfig.SERVICE_A, clientAB);

	MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
	params.put(FLOW_TYPE_PARAMETER, Collections.singletonList(FLOW_TYPE_TOKEN_EXCHANGE));
	ServiceCallResponse serviceBCallResponse = callService(ServicesConfig.SERVICE_B, clientAB, params);

	String modelAttr = "flowABCCall_" + FLOW_TYPE_TOKEN_EXCHANGE;
	model.put(modelAttr, fromUiApp(oauth2Authentication, request, serviceACallResponse, serviceBCallResponse));
	model.put("flowActive", true);

	return "index";
}
 
Example 3
Source File: FlowABCClientCredentialsController.java    From oauth2-protocol-patterns with Apache License 2.0 6 votes vote down vote up
@GetMapping
public String flowABC_ClientCredentials(@RegisteredOAuth2AuthorizedClient("client-ab") OAuth2AuthorizedClient clientAB,
										OAuth2AuthenticationToken oauth2Authentication,
										HttpServletRequest request,
										Map<String, Object> model) {

	ServiceCallResponse serviceACallResponse = callService(ServicesConfig.SERVICE_A, clientAB);

	MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
	params.put(FLOW_TYPE_PARAMETER, Collections.singletonList(FLOW_TYPE_CLIENT_CREDENTIALS));
	ServiceCallResponse serviceBCallResponse = callService(ServicesConfig.SERVICE_B, clientAB, params);

	String modelAttr = "flowABCCall_" + FLOW_TYPE_CLIENT_CREDENTIALS;
	model.put(modelAttr, fromUiApp(oauth2Authentication, request, serviceACallResponse, serviceBCallResponse));
	model.put("flowActive", true);

	return "index";
}
 
Example 4
Source File: UnionService.java    From seezoon-framework-all with Apache License 2.0 6 votes vote down vote up
/**
 * https://upay.10010.com/npfweb/NpfWeb/buyCard/checkPhoneVerifyCode?callback=checkSuccess&commonBean.phoneNo=13249073372&phoneVerifyCode=932453&timeStamp=0.3671002044464746
 * @throws ParseException
 * @throws Exception
 * sendSuccess('true') 返回格式
 */
@Test
public void checkChargeSms() throws ParseException, Exception {
	String mobile = "13249073372";
	CookieStore cookieStore = valueOperations.get(mobile);
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCookieStore(cookieStore);
	MultiValueMap<String,String> params =  new LinkedMultiValueMap<>();
	params.put("commonBean.phoneNo", Lists.newArrayList(mobile));
	params.put("phoneVerifyCode", Lists.newArrayList("904114"));
	params.put("timeStamp", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));

	String url = UriComponentsBuilder.fromHttpUrl("https://upay.10010.com/npfweb/NpfWeb/buyCard/checkPhoneVerifyCode").queryParams(params).build().toUriString();
	HttpGet request = new HttpGet(url);
	request.setHeader("Referer", "https://upay.10010.com/npfweb/npfbuycardweb/buycard_recharge_fill.htm");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else {
		throw new ServiceException("请求状态异常失败");
	}
}
 
Example 5
Source File: ResponseEntityDecoder.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> ResponseEntity<T> createResponse(Object instance, Response response) {

	MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
	for (String key : response.headers().keySet()) {
		headers.put(key, new LinkedList<>(response.headers().get(key)));
	}

	return new ResponseEntity<>((T) instance, headers,
			HttpStatus.valueOf(response.status()));
}
 
Example 6
Source File: UnionService.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
/**
 * https://uac.10010.com/portal/Service/SendMSG?callback=jQuery17205929719702722311_1528559748925&req_time=1528560335346&mobile=13249073372&_=1528560335347
 * @throws Exception 
 * @throws ParseException 
 */
@Test
public void sendSms() throws ParseException, Exception {
	CookieStore cookie = new BasicCookieStore() ;
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCookieStore(cookie);
	MultiValueMap<String,String> params =  new LinkedMultiValueMap<>();
	params.put("req_time", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));
	params.put("_=", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));
	params.put("mobile", Lists.newArrayList("13249073372"));
	String url = UriComponentsBuilder.fromHttpUrl("https://uac.10010.com/portal/Service/SendMSG").queryParams(params).build().toUriString();
	HttpGet request = new HttpGet(url);
	request.setHeader("Referer", "https://uac.10010.com/portal/custLogin");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else {
		throw new ServiceException("请求状态异常失败");
	}
	System.out.println("cookie:" + JSON.toJSONString(cookie));
	
}
 
Example 7
Source File: HierarchicalUriComponents.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private MultiValueMap<String, String> encodeQueryParams(String encoding) throws UnsupportedEncodingException {
	int size = this.queryParams.size();
	MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>(size);
	for (Map.Entry<String, List<String>> entry : this.queryParams.entrySet()) {
		String name = encodeUriComponent(entry.getKey(), encoding, Type.QUERY_PARAM);
		List<String> values = new ArrayList<String>(entry.getValue().size());
		for (String value : entry.getValue()) {
			values.add(encodeUriComponent(value, encoding, Type.QUERY_PARAM));
		}
		result.put(name, values);
	}
	return result;
}
 
Example 8
Source File: HierarchicalUriComponents.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private MultiValueMap<String, String> expandQueryParams(UriTemplateVariables variables) {
	int size = this.queryParams.size();
	MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>(size);
	for (Map.Entry<String, List<String>> entry : this.queryParams.entrySet()) {
		String name = expandUriComponent(entry.getKey(), variables);
		List<String> values = new ArrayList<String>(entry.getValue().size());
		for (String value : entry.getValue()) {
			values.add(expandUriComponent(value, variables));
		}
		result.put(name, values);
	}
	return result;
}
 
Example 9
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * To test enum parameters
 * To test enum parameters
 * <p><b>400</b> - Invalid request
 * <p><b>404</b> - Not found
 * @param enumHeaderStringArray Header parameter enum test (string array) (optional, default to new ArrayList&lt;String&gt;())
 * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg)
 * @param enumQueryStringArray Query parameter enum test (string array) (optional, default to new ArrayList&lt;String&gt;())
 * @param enumQueryString Query parameter enum test (string) (optional, default to -efg)
 * @param enumQueryInteger Query parameter enum test (double) (optional)
 * @param enumQueryDouble Query parameter enum test (double) (optional)
 * @param enumFormStringArray Form parameter enum test (string array) (optional, default to $)
 * @param enumFormString Form parameter enum test (string) (optional, default to -efg)
 * @return ResponseEntity&lt;Void&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Void> testEnumParametersWithHttpInfo(List<String> enumHeaderStringArray, String enumHeaderString, List<String> enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List<String> enumFormStringArray, String enumFormString) throws RestClientException {
    Object postBody = null;
    
    String path = apiClient.expandPath("/fake", 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();

    queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "enum_query_string_array", enumQueryStringArray));
    queryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_query_string", enumQueryString));
    queryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_query_integer", enumQueryInteger));
    queryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_query_double", enumQueryDouble));

    if (enumHeaderStringArray != null)
    headerParams.add("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray));
    if (enumHeaderString != null)
    headerParams.add("enum_header_string", apiClient.parameterToString(enumHeaderString));

    if (enumFormStringArray != null)
        formParams.put("enum_form_string_array", enumFormStringArray);
    if (enumFormString != null)
        formParams.add("enum_form_string", enumFormString);

    final String[] accepts = { };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { 
        "application/x-www-form-urlencoded"
    };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] {  };

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 10
Source File: MapAnnotationAttributeExtractorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void assertEnrichAndValidateAttributes(Map<String, Object> sourceAttributes, Map<String, Object> expected) {
	Class<? extends Annotation> annotationType = ImplicitAliasesContextConfig.class;

	// Since the ordering of attribute methods returned by the JVM is
	// non-deterministic, we have to rig the attributeAliasesCache in AnnotationUtils
	// so that the tests consistently fail in case enrichAndValidateAttributes() is
	// buggy.
	//
	// Otherwise, these tests would intermittently pass even for an invalid
	// implementation.
	Map<Class<? extends Annotation>, MultiValueMap<String, String>> attributeAliasesCache =
			(Map<Class<? extends Annotation>, MultiValueMap<String, String>>) AnnotationUtilsTests.getCache("attributeAliasesCache");

	// Declare aliases in an order that will cause enrichAndValidateAttributes() to
	// fail unless it considers all aliases in the set of implicit aliases.
	MultiValueMap<String, String> aliases = new LinkedMultiValueMap<String, String>();
	aliases.put("xmlFile", Arrays.asList("value", "groovyScript", "location1", "location2", "location3"));
	aliases.put("groovyScript", Arrays.asList("value", "xmlFile", "location1", "location2", "location3"));
	aliases.put("value", Arrays.asList("xmlFile", "groovyScript", "location1", "location2", "location3"));
	aliases.put("location1", Arrays.asList("xmlFile", "groovyScript", "value", "location2", "location3"));
	aliases.put("location2", Arrays.asList("xmlFile", "groovyScript", "value", "location1", "location3"));
	aliases.put("location3", Arrays.asList("xmlFile", "groovyScript", "value", "location1", "location2"));

	attributeAliasesCache.put(annotationType, aliases);

	MapAnnotationAttributeExtractor extractor = new MapAnnotationAttributeExtractor(sourceAttributes, annotationType, null);
	Map<String, Object> enriched = extractor.getSource();

	assertEquals("attribute map size", expected.size(), enriched.size());
	expected.keySet().stream().forEach( attr ->
		assertThat("for attribute '" + attr + "'", enriched.get(attr), is(expected.get(attr))));
}
 
Example 11
Source File: UnionService.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
/**
 * https://uac.10010.com/portal/Service/MallLogin?callback=jQuery17205929719702722311_1528559748927&
 * req_time=1528560369879&redirectURL=http%3A%2F%2Fwww.10010.com&userName=13249073372&
 * password=844505&pwdType=02&productType=01&redirectType=06&rememberMe=1&_=1528560369879
 * @throws Exception 
 * @throws ParseException 
 */
@Test
public void login() throws ParseException, Exception {
	HttpClientContext httpClientContext = HttpClientContext.create();
	String mobile = "13249073372";
	MultiValueMap<String,String> params =  new LinkedMultiValueMap<>();
	params.put("req_time", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));
	params.put("_=", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));
	params.put("redirectURL", Lists.newArrayList("http%3A%2F%2Fwww.10010.com"));
	params.put("userName", Lists.newArrayList(mobile));
	params.put("password", Lists.newArrayList("950102"));
	params.put("pwdType", Lists.newArrayList("02"));
	params.put("productType", Lists.newArrayList("01"));
	params.put("redirectType", Lists.newArrayList("06"));
	params.put("rememberMe", Lists.newArrayList("1"));

	String url = UriComponentsBuilder.fromHttpUrl("https://uac.10010.com/portal/Service/MallLogin").queryParams(params).build().toUriString();
	HttpGet request = new HttpGet(url);
	request.setHeader("Referer", "https://uac.10010.com/portal/custLogin");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else {
		throw new ServiceException("请求状态异常失败");
	}
	CookieStore cookie = httpClientContext.getCookieStore();
	System.out.println("cookie:" + JSON.toJSONString(cookie));
	valueOperations.set(mobile, cookie, 60, TimeUnit.MINUTES);
}
 
Example 12
Source File: HttpSyncDataService.java    From soul with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void doLongPolling() {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16);
    for (ConfigGroupEnum group : ConfigGroupEnum.values()) {
        ConfigData<?> cacheConfig = GROUP_CACHE.get(group);
        String value = String.join(",", cacheConfig.getMd5(), String.valueOf(cacheConfig.getLastModifyTime()));
        params.put(group.name(), Lists.newArrayList(value));
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    HttpEntity httpEntity = new HttpEntity(params, headers);
    for (String server : serverList) {
        String listenerUrl = server + "/configs/listener";
        log.debug("request listener configs: [{}]", listenerUrl);
        try {
            String json = this.httpClient.postForEntity(listenerUrl, httpEntity, String.class).getBody();
            log.debug("listener result: [{}]", json);
            JsonArray groupJson = GSON.fromJson(json, JsonObject.class).getAsJsonArray("data");
            if (groupJson != null) {
                // fetch group configuration async.
                ConfigGroupEnum[] changedGroups = GSON.fromJson(groupJson, ConfigGroupEnum[].class);
                if (ArrayUtils.isNotEmpty(changedGroups)) {
                    log.info("Group config changed: {}", Arrays.toString(changedGroups));
                    this.fetchGroupConfig(changedGroups);
                }
            }
            break;
        } catch (RestClientException e) {
            log.error("listener configs fail, can not connection this server:[{}]", listenerUrl);
            /*  ex = new SoulException("Init cache error, serverList:" + serverList, e);*/
            // try next server, if have another one.
        }
    }
}
 
Example 13
Source File: LinkMap.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
public static LinkMap buildLinkMap(List<Node> nodeList, TraceState traceState, long collectorAcceptTime, ServiceTypeRegistryService serviceTypeRegistryService) {
    final MultiValueMap<LongPair, Node> spanToLinkMap = new LinkedMultiValueMap<>();

    // for performance & remove duplicate span
    final List<Node> duplicatedNodeList = new ArrayList<>();
    for (Node node : nodeList) {
        final SpanBo span = node.getSpanBo();
        final LongPair spanIdPairKey = new LongPair(span.getParentSpanId(), span.getSpanId());
        // check duplicated span
        Node firstNode = spanToLinkMap.getFirst(spanIdPairKey);
        if (firstNode == null) {
            spanToLinkMap.add(spanIdPairKey, node);
        } else {
            ServiceType serviceType = serviceTypeRegistryService.findServiceType(span.getServiceType());
            if (serviceType.isQueue() && firstNode.getSpanBo().getServiceType() == serviceType.getCode()) {
                spanToLinkMap.add(spanIdPairKey, node);
            } else {
                traceState.progress();
                // duplicated span, choose focus span
                if (span.getCollectorAcceptTime() == collectorAcceptTime) {
                    // replace value
                    spanToLinkMap.put(spanIdPairKey, Collections.singletonList(node));
                    duplicatedNodeList.add(node);
                    logger.warn("Duplicated span - choose focus {}", node);
                } else {
                    // add remove list
                    duplicatedNodeList.add(node);
                    logger.warn("Duplicated span - ignored second {}", node);
                }
            }
        }
    }

    // clean duplicated node
    nodeList.removeAll(duplicatedNodeList);
    return new LinkMap(spanToLinkMap, duplicatedNodeList);
}
 
Example 14
Source File: MapToMapConverterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void multiValueMapToMultiValueMap() throws Exception {
	DefaultConversionService.addDefaultConverters(conversionService);
	MultiValueMap<String, Integer> source = new LinkedMultiValueMap<>();
	source.put("a", Arrays.asList(1, 2, 3));
	source.put("b", Arrays.asList(4, 5, 6));
	TypeDescriptor targetType = new TypeDescriptor(getClass().getField("multiValueMapTarget"));

	MultiValueMap<String, String> converted = (MultiValueMap<String, String>) conversionService.convert(source, targetType);
	assertThat(converted.size(), equalTo(2));
	assertThat(converted.get("a"), equalTo(Arrays.asList("1", "2", "3")));
	assertThat(converted.get("b"), equalTo(Arrays.asList("4", "5", "6")));
}
 
Example 15
Source File: MapAnnotationAttributeExtractorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void assertEnrichAndValidateAttributes(Map<String, Object> sourceAttributes, Map<String, Object> expected) throws Exception {
	Class<? extends Annotation> annotationType = ImplicitAliasesContextConfig.class;

	// Since the ordering of attribute methods returned by the JVM is non-deterministic,
	// we have to rig the attributeAliasesCache in AnnotationUtils so that the tests
	// consistently fail in case enrichAndValidateAttributes() is buggy.
	// Otherwise, these tests would intermittently pass even for an invalid implementation.
	Field cacheField = AnnotationUtils.class.getDeclaredField("attributeAliasesCache");
	cacheField.setAccessible(true);
	Map<Class<? extends Annotation>, MultiValueMap<String, String>> attributeAliasesCache =
			(Map<Class<? extends Annotation>, MultiValueMap<String, String>>) cacheField.get(null);

	// Declare aliases in an order that will cause enrichAndValidateAttributes() to
	// fail unless it considers all aliases in the set of implicit aliases.
	MultiValueMap<String, String> aliases = new LinkedMultiValueMap<>();
	aliases.put("xmlFile", Arrays.asList("value", "groovyScript", "location1", "location2", "location3"));
	aliases.put("groovyScript", Arrays.asList("value", "xmlFile", "location1", "location2", "location3"));
	aliases.put("value", Arrays.asList("xmlFile", "groovyScript", "location1", "location2", "location3"));
	aliases.put("location1", Arrays.asList("xmlFile", "groovyScript", "value", "location2", "location3"));
	aliases.put("location2", Arrays.asList("xmlFile", "groovyScript", "value", "location1", "location3"));
	aliases.put("location3", Arrays.asList("xmlFile", "groovyScript", "value", "location1", "location2"));

	attributeAliasesCache.put(annotationType, aliases);

	MapAnnotationAttributeExtractor extractor = new MapAnnotationAttributeExtractor(sourceAttributes, annotationType, null);
	Map<String, Object> enriched = extractor.getSource();

	assertEquals("attribute map size", expected.size(), enriched.size());
	expected.forEach((attr, expectedValue) -> assertThat("for attribute '" + attr + "'", enriched.get(attr), is(expectedValue)));
}
 
Example 16
Source File: BodyInsertersTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-16350
public void fromMultipartDataWithMultipleValues() {
	MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
	map.put("name", Arrays.asList("value1", "value2"));
	BodyInserters.FormInserter<Object> inserter = BodyInserters.fromMultipartData(map);

	MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create("http://example.com"));
	Mono<Void> result = inserter.insert(request, this.context);
	StepVerifier.create(result).expectComplete().verify();

	StepVerifier.create(DataBufferUtils.join(request.getBody()))
			.consumeNextWith(dataBuffer -> {
				byte[] resultBytes = new byte[dataBuffer.readableByteCount()];
				dataBuffer.read(resultBytes);
				DataBufferUtils.release(dataBuffer);
				String content = new String(resultBytes, StandardCharsets.UTF_8);
				assertThat(content, containsString("Content-Disposition: form-data; name=\"name\"\r\n" +
						"Content-Type: text/plain;charset=UTF-8\r\n" +
						"Content-Length: 6\r\n" +
						"\r\n" +
						"value1"));
				assertThat(content, containsString("Content-Disposition: form-data; name=\"name\"\r\n" +
						"Content-Type: text/plain;charset=UTF-8\r\n" +
						"Content-Length: 6\r\n" +
						"\r\n" +
						"value2"));
			})
			.expectComplete()
			.verify();
}
 
Example 17
Source File: HierarchicalUriComponents.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private MultiValueMap<String, String> encodeQueryParams(String encoding) throws UnsupportedEncodingException {
	int size = this.queryParams.size();
	MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>(size);
	for (Map.Entry<String, List<String>> entry : this.queryParams.entrySet()) {
		String name = encodeUriComponent(entry.getKey(), encoding, Type.QUERY_PARAM);
		List<String> values = new ArrayList<String>(entry.getValue().size());
		for (String value : entry.getValue()) {
			values.add(encodeUriComponent(value, encoding, Type.QUERY_PARAM));
		}
		result.put(name, values);
	}
	return result;
}
 
Example 18
Source File: UnionService.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
/**
 * https://upay.10010.com/npfweb/NpfWeb/buyCard/sendPhoneVerifyCode?callback=sendSuccess&commonBean.phoneNo=13249073372&timeStamp=0.474434596328998
 * @throws ParseException
 * @throws Exception
 * sendSuccess('true') 返回格式
 */
@Test
public void chargeSms() throws ParseException, Exception {
	String mobile = "13249073372";
	CookieStore cookieStore = valueOperations.get(mobile);
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCookieStore(cookieStore);
	MultiValueMap<String,String> params =  new LinkedMultiValueMap<>();
	params.put("commonBean.phoneNo", Lists.newArrayList(mobile));
	params.put("timeStamp", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));

	String url = UriComponentsBuilder.fromHttpUrl("https://upay.10010.com/npfweb/NpfWeb/buyCard/sendPhoneVerifyCode").queryParams(params).build().toUriString();
	HttpGet request = new HttpGet(url);
	request.setHeader("Referer", "https://uac.10010.com/portal/custLogin");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else {
		throw new ServiceException("请求状态异常失败");
	}
}
 
Example 19
Source File: EchoTest.java    From Milkomeda with MIT License 5 votes vote down vote up
@Test
public void testOpenAccount() throws Exception {
    MultiValueMap<String, String> reqParams = new LinkedMultiValueMap<>();
    reqParams.put("uid", Collections.singletonList("1101"));
    reqParams.put("name", Collections.singletonList("yiz"));
    reqParams.put("id_no", Collections.singletonList("14324357894594483"));

    val ret = mockMvc.perform(MockMvcRequestBuilders.get("/echo/account/open")
            .params(reqParams)
            .contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andReturn().getResponse().getContentAsString();
    System.out.println(ret);
}
 
Example 20
Source File: MapToMapConverterTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void multiValueMapToMultiValueMap() throws Exception {
	DefaultConversionService.addDefaultConverters(conversionService);
	MultiValueMap<String, Integer> source = new LinkedMultiValueMap<>();
	source.put("a", Arrays.asList(1, 2, 3));
	source.put("b", Arrays.asList(4, 5, 6));
	TypeDescriptor targetType = new TypeDescriptor(getClass().getField("multiValueMapTarget"));

	MultiValueMap<String, String> converted = (MultiValueMap<String, String>) conversionService.convert(source, targetType);
	assertThat(converted.size(), equalTo(2));
	assertThat(converted.get("a"), equalTo(Arrays.asList("1", "2", "3")));
	assertThat(converted.get("b"), equalTo(Arrays.asList("4", "5", "6")));
}