java 使用地图为使用 RestTemplate 的休息调用设置参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31342841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:28:12  来源:igfitidea点击:

Using a map to set parameters for a rest call using RestTemplate

javaspringspring-mvcspring-restcontroller

提问by Emilien Brigand

I am currently using a piece of code to set parameters and I do a REST call to a URL using restTemplate, it works fine:

我目前正在使用一段代码来设置参数,并使用 restTemplate 对 URL 进行 REST 调用,它工作正常:

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("grant_type", grantType);
map.add("client_id", clientId);
map.add("client_secret", clientSecret);
HttpEntity<?> entity = new HttpEntity<Object>(map);
restTemplate.exchange("myurl", HttpMethod.POST, entity, Void.class);

But if I am using a LinkedMultiValueMapit's because I looked on the web ;)

但是,如果我使用的是LinkedMultiValueMap它,那是因为我在网上查看了 ;)

And if I replace it by a HashMap, it works as well, so can anyone tell me the advantage of using a LinkedMultiValueMap?

如果我用 a 替换它HashMap,它也可以工作,那么谁能告诉我使用 a 的好处LinkedMultiValueMap

Code with HashMap:

代码HashMap

Map<String, String> map = new HashMap<String, String>();
map.put("grant_type", grantType);
map.put("client_id", clientId);
map.put("client_secret", clientSecret);
HttpEntity<?> entity = new HttpEntity<Object>(map);
restTemplate.exchange("myurl", HttpMethod.POST, entity, Void.class);

I can see we can preserve the order of the parameters in the LinkedMultiValueMap, but it does not matter in my project... And so if orders matters I still could use a LinkedHashMap

我可以看到我们可以保留 中参数的顺序LinkedMultiValueMap,但这在我的项目中并不重要......所以如果订单很重要我仍然可以使用LinkedHashMap

EDIT:

编辑:

It looks like I need the MultiValueMap if I use APPLICATION_FORM_URLENCODED and HashMap, this code throw an exception :

如果我使用 APPLICATION_FORM_URLENCODED 和 HashMap,看起来我需要 MultiValueMap,此代码抛出异常:

Map<String, String> map = new HashMap<String, String>();
map.add("grant_type", grantType);
map.add("client_id", clientId);
map.add("client_secret", clientSecret);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<?> entity = new HttpEntity<Object>(map, headers);
restTemplate.exchange("myurl", HttpMethod.POST, entity, Void.class);

Exception:

例外:

org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [java.util.HashMap] and content type [application/x-www-form-urlencoded]
        at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:784)
        at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:567)
        at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:530)
        at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:448)
        at uk.co.wowcher.marketplace.commons.rest.RestTemplateUtils.getForEntity(RestTemplateUtils.java:54)
        at uk.co.wowcher.marketplace.submission.service.ParameterService.getProductParameterVOs(ParameterService.java:38)
        at uk.co.wowcher.marketplace.submission.service.ParameterService$$FastClassBySpringCGLIB$f87231d.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
        at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
        at uk.co.wowcher.marketplace.submission.logging.MarketplaceLogger.logMethodCalls(MarketplaceLogger.java:27)
        at sun.reflect.GeneratedMethodAccessor72.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:483)
        at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:621)
        at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:610)
        at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:68)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
        at uk.co.xxx.marketplace.submission.service.ParameterService$$EnhancerBySpringCGLIB$$a52b80b.getProductParameterVOs(<generated>)
        at uk.co.xxx.marketplace.submission.service.SubmissionService.getAgreementData(SubmissionService.java:449)
       at uk.co.xxx.marketplace.submission.service.SubmissionService$$FastClassBySpringCGLIB$bbe798.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)

So, it looks like that setting some parameters with a HashMap is not a good idea at all... So I removed the accepted answer for now, waiting more explanation on this point... And I have the suitable converter (converters.add(new FormHttpMessageConverter());), I mean if I use a MultiValueMap I don't have the exception, so the HashMap is the problem!

所以,看起来用 HashMap 设置一些参数根本不是一个好主意......所以我现在删除了接受的答案,等待关于这一点的更多解释......我有合适的转换器(converters.add(new FormHttpMessageConverter());),我意味着如果我使用 MultiValueMap 我没有异常,所以 HashMap 是问题!

回答by aryn.galadar

The only real advantage of using a LinkedMultiValueMapover other Mapimplementations is that it can store multiple values.

LinkedMultiValueMap与其他Map实现相比,使用 a 的唯一真正优势是它可以存储多个值。

This is useful if you need to pass multiple values for the same key (for instance, if you need to pass a set of form checkbox values).

如果您需要为同一个键传递多个值(例如,如果您需要传递一组表单复选框值),这将非常有用。

See the JavaDoc here.

请参阅此处的 JavaDoc 。

In your case, since you only have one value per key, you should be able to safely use a HashMap.

在您的情况下,由于每个键只有一个值,因此您应该能够安全地使用HashMap.

回答by Kanagaraj M

MultiValueMapis used to store more than one value for a single KEY(Map(key:ArrayOfValues[])) while LinkedMultiValueMapdoes the same thing but with insertion order maintained. In your case, HashMapis enough because LinkedMultiValueMapperformance will be slower than HashMapand HashMapis not required for your scenario.

MultiValueMap用于为单个 KEY( Map(key:ArrayOfValues[]))存储多个值,同时LinkedMultiValueMap执行相同的操作,但保持插入顺序。在您的情况下,HashMap就足够了,因为LinkedMultiValueMap性能会比您的方案慢HashMap并且HashMap不需要。