我已经用 restTemplate 解决了这个问题。
请看一些代码示例:
public String uploadPhoto(File file, String token) throws ClientRequestException {
try {
MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
UrlResource urlr = new UrlResource("file:" + file.getAbsolutePath());
form.add("attachment", urlr);
WsUrl wsUrl = requestForObjectMultipart("/uploadProfilePhoto.json", form, WsUrl.class, token);
return wsUrl.getUrl();
} catch (MalformedURLException e) {
throw new ClientRequestException("Something went wrong with file upload");
}
}
protected <T extends ErrorAware> T requestForObjectMultipart(String methodUrl, Object r, Class<T> c, String token) throws ClientRequestException{
HttpHeaders headers = new HttpHeaders();
headers.add(SECURITY_TOKEN,token);
//Need to set content type here to avoid convertion with Jackson message converter
headers.add("Content-Type", "multipart/form-data");
return requestForObjectWithHeaders(methodUrl, r, c, HttpMethod.POST, headers);
}
protected <T extends ErrorAware> T requestForObjectWithHeaders(String methodUrl, Object r, Class<T> c, HttpMethod method, HttpHeaders headers) throws ClientRequestException{
T result = restTemplate.exchange( getBaseUrl() + getApiUrlPref() + methodUrl, method, new HttpEntity<Object>(r,headers), c).getBody();
if( result.hasError() )
throw new ClientRequestException(result.getError());
return result;
}
字符串令牌 - 它只是我们其余服务上的安全令牌(作为自定义 HTTP 标头提供)。它可以提供如何在请求中设置“自定义标头”的示例。注意:请注意返回的数据(上传文件后来自网络服务)被解析为 JSON 对象。如果你不想要这个 - 你可以简单地忽略 restTemplate.exchange() 方法的结果。
我在 Spring 配置中的 restTemplate 初始化:
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<ref bean="jsonConverter"/>
<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
</list>
</property>
...
</bean>
<!-- To enable @RequestMapping process on type level and method level -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonConverter"/>
</list>
</property>
</bean>
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json"/>
</bean>