编码网址挣扎

时间:2017-03-25 14:49:58

标签: java url uri resttemplate encoder

我有一个String url。最后一部分是包含[和]的过滤器。

[{'field':'campaign.effective_status','operator':'IN','value':['ACTIVE']}]

无论我尝试什么,我都无法编码​​并将其作为有效的URL或URI发送。

错误:

java.lang.IllegalArgumentException: Not enough variable values available to expand ''field''] with root cause

这是因为[。

执行时:

String response = restTemplate.getForObject(fbUrl, String.class);

失败了。

我尝试将过滤器添加为变量。

String response = restTemplate.getForObject(fbUrl, String.class,"["+filter+"]");

成功,但不应用过滤器。

当我使用它时,

fbUrl = fbUrl +URLEncoder.encode("[","UTF-8")+URLEncoder.encode(request.getFilters(),"UTF-8")+URLEncoder.encode("]","UTF-8");

我明白了:

https://graph.facebook.com/v2.8/act_323342434/insights?level=campaign&fields=impressions&access_token=EAAUnOB1oiQgBAFeFVZCkOUC30JXgM9YHRl3C8ZCpubteRK9DtKbVSzgS8lR3N7zzZCCO7Bp7CIGCp7BqAmKbywDZAh71bcLW2YpQOQwZCx5v6xCJXXA6ZBx9QcjxNH5GCZBBXLeIhusnZAjZBdWocjhoOJXAYZCENPaUIN3kuukJQUggZDZD&time_increment=&sort=date_start_ascending&time_range[since]=2017-02-01&time_range[until]=2017-02-28&filtering=%5B%7B%27field%27%3A%27campaign.effective_status%27%2C%27operator%27%3A%27IN%27%2C%27value%27%3A%5B%27ACTIVE%27%5D%7D%5D

但后来我得到了:

 org.springframework.web.client.HttpClientErrorException: 400 Bad Request] with root cause

感谢任何帮助。

在realSkeptic的帮助下,我找到了解决方案:

String baseUrl = "https://graph.facebook.com/v2.8/";
baseUrl = baseUrl + request.getAdvertiserId() + "/insights?level=" + request.getDimensions() +"&";
baseUrl = baseUrl +URLEncoder.encode("fields", "UTF-8")+"="+URLEncoder.encode(request.getMetrics(), "UTF-8") +"&";
baseUrl = baseUrl +URLEncoder.encode("access_token", "UTF-8")+"="+URLEncoder.encode(request.getAccessToken(), "UTF-8") +"&";
baseUrl = baseUrl +URLEncoder.encode("time_increment", "UTF-8")+"="+URLEncoder.encode(request.getTimeIncrement(), "UTF-8") +"&";
baseUrl = baseUrl +URLEncoder.encode("sort", "UTF-8")+"="+URLEncoder.encode(request.getSort(), "UTF-8") +"&";
baseUrl = baseUrl +URLEncoder.encode("time_range[since]", "UTF-8")+"="+URLEncoder.encode(request.getStartDate(), "UTF-8") +"&";
baseUrl = baseUrl +URLEncoder.encode("time_range[until]", "UTF-8")+"="+URLEncoder.encode(request.getEndDate(), "UTF-8") +"&";
baseUrl = baseUrl +URLEncoder.encode("filtering", "UTF-8")+"="+URLEncoder.encode("["+request.getFilters()+"]", "UTF-8");
String response = restTemplate.getForObject(baseUrl, String.class); 

0 个答案:

没有答案