骆驼:改变流编码

时间:2014-02-05 06:26:20

标签: apache-camel

我正在使用该路由从http接收数据流:

from("direct:foo").
to("http://foo.com/bar.html").
to("file:///tmp/bar.html")

HTTP流附带Windows-1251编码。我想在运行时重新编码为UTF-8,然后存储到文件中。

如何使用标准camel方式做到这一点?

2 个答案:

答案 0 :(得分:7)

我认为vikingsteve的解决方案错过了一步。输入流包含编码为CP1251的字符。将输入流内容转换为字符串时,该流中的字符不会更改其编码。您需要指定在解码时对编码字符的实体使用的相同字符编码方案。否则你会得到不良结果。

<route id="process_umlaug_file" startupOrder="2">
    <from uri="file:///home/steppra1/Downloads?fileName=input_umlauts.txt"/>
    <convertBodyTo type="java.lang.String" charset="ISO-8859-1"/>
    <to uri="file:///home/steppra1/Downloads?fileName=output_umlauts.txt&amp;charset=UTF-8"/>
</route>

我测试了这个读取包含德语变音符号的CP1251编码文件:

steppra1@steppra1-linux-mint ~/Downloads $ file input_umlauts.txt 
input_umlauts.txt: ISO-8859 text, with CRLF line terminators

steppra1@steppra1-linux-mint ~/Downloads $ file output_umlauts.txt 
output_umlauts.txt: UTF-8 Unicode text, with CRLF line terminators

使用解码然后重新编码的两个步骤产生正确编码的德语变音符号。如果我改变以上路线

<route id="process_umlaug_file" startupOrder="2">
    <from uri="file:///home/steppra1/Downloads?fileName=input_umlauts.txt"/>
    <convertBodyTo type="java.lang.String" charset="UTF-8"/>
    <to uri="file:///home/steppra1/Downloads?fileName=output_umlauts.txt"/>
</route>

然后输出文件仍然是UTF-8编码,可能是因为这是我的平台默认值,但是变音符号是乱码。

答案 1 :(得分:6)

请查看.convertBodyTo() - 特别是charset参数。

from("direct:foo").
to("http://foo.com/bar.html").
convertBodyTo(String.class, "UTF-8")
to("file:///tmp/bar.html")

参考:http://camel.apache.org/convertbodyto.html