带括号的RestTemplate请求(" {","}")

时间:2017-05-11 13:50:38

标签: resttemplate

我想通过RestTemplate发送请求。但我的网址有大括号(' {','}'),因此我有例外:"没有足够的变量值可用于展开...&#34 ;

我尝试通过uri

UriComponentsBuilder builder = UriComponentsBuilder.fromPath(url);
UriComponents uriComponents = builder.build();
URI uri = uriComponents.toUri();

但我得到了新的例外:" protocol = https host = null"。

如何使用我的网址发送请求?在URL中必须是大括号。

我的代码:

String url = "https://api.vk.com/method/execute?code=return[API.users.search({"count":1})];&access_token...
String result = restTemplate.getForObject(url, String.class);

1 个答案:

答案 0 :(得分:1)

下面的代码使用UriComponentsBuilder加密uri,使用RestTemplate添加查询参数,如果有的话还设置HttpHeaders

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);
    }

希望这会有所帮助并祝你好运!