Spring RestTemplate GET 带参数 [英] Spring RestTemplate GET with parameters

查看:63
本文介绍了Spring RestTemplate GET 带参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须进行包含自定义标头和查询参数的 REST 调用.我只设置了我的 HttpEntity 标题(没有正文),我使用了 RestTemplate.exchange() 方法,如下所示:

I have to make a REST call that includes custom headers and query parameters. I set my HttpEntity with just the headers (no body), and I use the RestTemplate.exchange() method as follows:

HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");

Map<String, String> params = new HashMap<String, String>();
params.put("msisdn", msisdn);
params.put("email", email);
params.put("clientVersion", clientVersion);
params.put("clientType", clientType);
params.put("issuerName", issuerName);
params.put("applicationName", applicationName);

HttpEntity entity = new HttpEntity(headers);

HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, params);

这在客户端失败,dispatcher servlet 无法将请求解析到处理程序.调试了一下,好像没有发送请求参数.

This fails at the client end with the dispatcher servlet being unable to resolve the request to a handler. Having debugged it, it looks like the request parameters are not being sent.

当我使用请求正文和没有查询参数的 POST 进行交换时,它工作得很好.

When I do a an exchange with a POST using a request body and no query parameters it works just fine.

有人有什么想法吗?

推荐答案

好吧,所以我是个白痴,我将查询参数与 url 参数混淆了.我有点希望有一种更好的方法来填充我的查询参数,而不是一个丑陋的串联字符串,但我们就是这样.这只是使用正确参数构建 URL 的一种情况.如果您将它作为字符串传递,Spring 也会为您处理编码.

OK, so I'm being an idiot and I'm confusing query parameters with url parameters. I was kinda hoping there would be a nicer way to populate my query parameters rather than an ugly concatenated String but there we are. It's simply a case of build the URL with the correct parameters. If you pass it as a String Spring will also take care of the encoding for you.

这篇关于Spring RestTemplate GET 带参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆