RestTemplate request with braces (“{”, “}”)

匆匆过客 提交于 2021-01-28 04:44:52

问题


I want to send request through RestTemplate. But my url has braces ('{', '}'), and therefore I have exception: "Not enough variable values available to expand ...".

I try do it through uri

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

But I got new exception:"protocol = https host = null".

How I can send request with my URL? In URL must be braces.

My code:

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:


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!



来源:https://stackoverflow.com/questions/43917408/resttemplate-request-with-braces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!