带大括号的 RestTemplate 请求(“{"、“}") [英] RestTemplate request with braces ("{", "}")
问题描述
我想通过 RestTemplate 发送请求.但是我的网址有大括号('{','}'),因此我有例外:没有足够的变量值可用于扩展......".
I want to send request through RestTemplate. But my url has braces ('{', '}'), and therefore I have exception: "Not enough variable values available to expand ...".
我尝试通过uri来做
UriComponentsBuilder builder = UriComponentsBuilder.fromPath(url);
UriComponents uriComponents = builder.build();
URI uri = uriComponents.toUri();
但是我得到了新的异常:protocol = https host = null".
But I got new exception:"protocol = https host = null".
如何使用我的 URL 发送请求?在 URL 中必须是大括号.
How I can send request with my URL? In URL must be braces.
我的代码:
String url = "https://api.vk.com/method/execute?code=return[API.users.search({"count":1})];&access_token...
String result = restTemplate.getForObject(url, String.class);
推荐答案
下面的代码使用 UriComponentsBuilder
加密 uri,使用 RestTemplate
添加查询参数并设置 HttpHeaders
如果有的话.
Below code encrypts the uri using UriComponentsBuilder
, adds query params using RestTemplate
and also sets HttpHeaders
if any.
public HttpEntity<String> getEntityByUri() {
String req = "https://api.vk.com/method/execute";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(req)
.queryParam("code",
"return[API.users.search({"count":1})]");
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.ALL));
HttpEntity<String> httpEntity = new HttpEntity<String>(headers);
return new RestTemplate().exchange(builder.build().encode().toUri(), HttpMethod.GET, httpEntity, String.class);
}
希望这会有所帮助并祝您好运!
Hope this helps and good luck!
这篇关于带大括号的 RestTemplate 请求(“{"、“}")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!