gpt4 book ai didi

Spring RestTemplate PostforObject : Unsupported Media Type

转载 作者:可可西里 更新时间:2023-11-01 15:28:38 26 4
gpt4 key购买 nike

我正在尝试执行 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)

有什么想法吗?

最佳答案

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

关于Spring RestTemplate PostforObject : Unsupported Media Type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12257689/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com