4

我正在尝试执行 RESTful Web 服务,但是,当我发送请求时,发生 HttpClientErrorException 并显示“415 Unsupported Media Type”作为消息。

这是服务调用的代码:

MultiValueMap<String, String> request = new LinkedMultiValueMap<String, String>();
request.add(val1, "xxxxx");
request.add(val2, "************");
request.add(val3, "xxx");
request.add("type", "AUTHENTICATE");

String response = restTemplate.postForObject(url, request, String.class);
System.out.println(response.toString());

restTemplate 是从 applicationContext.xml 连接的,FormHttpMessageConverter 作为它的 messageConverter。

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg name="requestFactory" ref="httpClientFactory"/>
<property name="messageConverters">
    <list>
        <bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
</list>
</property>
</bean>

<bean id="httpClientFactory" class="org.springframework.http.client.CommonsClientHttpRequestFactory">
    <constructor-arg ref="httpClient"/>
</bean>
<bean id="httpClientParams" class="org.apache.commons.httpclient.params.HttpClientParams">
    <property name="authenticationPreemptive" value="true"/>
    <property name="connectionManagerClass"
                  value="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager"/>
</bean>
<bean id="httpClient" class="org.apache.commons.httpclient.HttpClient">
    <constructor-arg ref="httpClientParams"/>
</bean>

这是发生的异常:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:76)
    at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:486)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:443)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:401)
    at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:279)
    at ph.com.smart.drawbridge.commons.diameter.DiameterClient.post(DiameterClient.java:21)

有任何想法吗?

4

2 回答 2

4

当您的客户端发送服务器不知道如何处理的媒体类型的请求时,就会发生此问题。例如,您处理的服务器方法url可以处理类型的请求,application/json但您发送了text/xml. 服务器无法处理此类请求。为了解决这个问题,找出content-type服务器期望的(媒体类型),在你的restTemplate对象中设置一个标头来设置content-type:application/json(替换application/json为服务器期望的任何内容)。此外,请确保以正确的格式发送请求(如果我们正在谈论json您需要具有jackson可以将对象序列化为对象的依赖项json)。

于 2013-07-05T09:08:46.777 回答
0

您现在可能不需要这个,但我会为将来遇到此类问题的任何人分享这个。

正如@Avi 指出的那样,当您的服务器期望与您在请求中发送的媒体类型不同时,确实会发生此问题。

就我而言,我正在发送表单数据,MediaType.APPLICATION_JSON而我的服务器需要 Mutipart 表单数据。在我的请求中添加以下标头解决了我的问题:

HttpHeaders headers = getBasicAuthHttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
于 2016-09-22T15:37:45.273 回答