3

我想从 http 响应中读取字符串,就像这样。我正在尝试这样做[见下文],但它正在抛出错误。

1.客户

String string=getForObject("http://127.0.0.1:6060/dc-server/rest/dataset/Book/meta", String.class);

2.服务器

@ResponseBody
@RequestMapping(value="/dataset/{datasetName}/meta", method=RequestMethod.GET)
public String getDatasetMeta(@PathVariable("datasetName") String datasetName) {
    return service.getDatasetMeta(datasetName);
}

spring mvc 配置文件

<bean id="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
</bean>
<bean id="stringHttpMessageConverter"  class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
    <property name="messageConverters">
        <list>
            <ref bean="jsonMessageConverter" />
            <ref bean="stringHttpMessageConverter"/>
        </list>
    </property>
</bean>

例外

    org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@19a6fa1; line: 1, column: 2]; nested exception is org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@19a6fa1; line: 1, column: 2]
    at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:127)
    at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:153)
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:81)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:446)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:401)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:199)
    at com.cgs.dc.client.rest.RestConnector.getDatasetMeta(RestConnector.java:55)
    at server/rest/dataset/Book/meta" resulted in 200 (OK)
14:01:05,395 DEBUG RestTemplate:78 - Reading [java.lang.String] as "application/json" using [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter@1371ddd]

响应正文

<dataset xmlns="http://sucsoft.com/DC_DEF" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ......
4

1 回答 1

3

您正在访问的服务返回的是 xml 响应,而不是 json 响应。您可能应该做的是使用 JAX-B 将该 xml 转换为真正的 java 对象。

使用这个 Eclipse 插件,您可以从您的 xml 文档中生成一个已注释的 java 类。然后,您可以在 restTemplate 中使用该类(它不需要任何特殊的 spring xml 配置)作为您希望将 xml 反序列化为的类。

像这样:

Response response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity(null), Response.class);

确保Response是带注释的类。

如果您只想要一个字符串,请确保 spring 没有尝试使用 json 消息转换器反序列化它。

于 2013-06-20T08:04:57.823 回答