【问题标题】:Passing special characters like E acute to JSON webservice using RestTemplate使用 RestTemplate 将 E 等特殊字符传递给 JSON Web 服务
【发布时间】:2015-03-20 04:26:59
【问题描述】:

我正在从数据库中获取数据并调用其余的 json 网络服务。我正在使用 spring restTemplate 来调用 web 服务。我添加了 spring 用来创建 json 的 jackson jar。 但是,当我们得到像 latin e 这样带有尖锐 É 的字符时,我会遇到问题。杰克逊不要逃避它并按原样传递,这里的 web 服务在另一端失败会给出 500 内部错误。我需要像\u0209一样传递它的unicode。 我尝试使用 StringEcapeUtils 来转换它,它被转换为 \u0209。 但这次RestTemplate 再次将其转义为 \u0209 并在目标系统上以 \u0209 的形式接收。

目标系统是另一个我们无法更改任何内容的系统。

我的 restTemplate 代码是:-

MultiValueMap<String, String> headers =
        new LinkedMultiValueMap<String, String>();
        headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE); //Note Content-Type as opposed to Accept

        HttpEntity<Object> entity = new HttpEntity<Object>(myRequest, headers);

        myResponse = restTemplate.postForObject(url, entity, responseClass );

【问题讨论】:

  • 可能是服务器有问题,因为您的Content-Type 标头没有指定charset

标签: json spring jackson special-characters resttemplate


【解决方案1】:

我猜服务器不知道如何解释您发送的内容。你试过了吗

MediaType mediaType = 
    new MediaType( "application" , "json" , Charset.forName( "UTF-8" ) ); 
headers.add( "Content-Type", mediaType );

干杯,

【讨论】:

  • 我会试试这个,但我不认为我的 resttemplate 有问题,它似乎是在序列化为 json 期间出现的问题。
【解决方案2】:

是的,问题是我的客户没有发送字符集。请注意,我更改了传递 Content-Type 的标题

我的新代码:-

MultiValueMap<String, String> headers =
    new LinkedMultiValueMap<String, String>();
    headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8"); //Note Content-Type as opposed to Accept

    HttpEntity<Object> entity = new HttpEntity<Object>(myRequest, headers);

    myResponse = restTemplate.postForObject(url, entity, responseClass );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多