Spring RestTemplate URL编码
问题内容:
我尝试使用springs resttemplate做一个简单的rest调用:
private void doLogout(String endpointUrl, String sessionId) {
template.getForObject("http://{enpointUrl}?method=logout&session={sessionId}", Object.class,
endpointUrl, sessionId);
}
其中endpointUrl变量包含诸如service.host.com/api/service.php之类的内容
不幸的是,我的呼叫导致org.springframework.web.client.ResourceAccessException:I /
O错误:service.host.com%2Fapi%2Fservice.php
因此,spring似乎在创建url之前先编码了我的endpointUrl字符串。有没有一种简单的方法可以防止弹簧这样做?
问候
问题答案:
取决于您使用的Spring版本。如果您的版本太旧,例如版本3.0.6.RELEASE,那么您将没有UriComponentsBuilderspring-web jar那样的便利。
您需要防止Spring RestTemplate对URL进行编码。您可以做的是:
import java.net.URI;
StringBuilder builder = new StringBuilder("http://");
builder.append(endpointUrl);
builder.append("?method=logout&session=");
builder.append(sessionId);
URI uri = URI.create(builder.toString());
restTemplate.getForObject(uri, Object.class);
我使用Spring 3.0.6.RELEASE版本对其进行了测试,并且可以正常工作。
简而言之,不要使用restTemplate.getForObject(String url,Object.class)
,而要使用restTemplate.getForObject(java.net.URI uri, Object.class)
请参阅Spring文档的rest-resttemplate-uri部分