我目前正在使用新的Camel REST DSL作为基础来开发基于REST的Java应用程序。 它主要的工作只是我通过一个REST客户端调用URL时发现(而不是说一个浏览器)的JSON的反应是“乱码”,并与我承担什么是错误的编码骆驼休息DSL响应编码
MyRouteBuilder来通过的.java
@Component
public class MyRouteBuilder extends RouteBuilder{
@Autowired
LocalEnvironmentBean environmentBean;
@Override
public void configure() throws Exception {
restConfiguration().component("jetty").host("0.0.0.0").port(80)
.bindingMode(RestBindingMode.auto);
rest("/testApp")
.get("/data").route()
.to("bean:daoService?method=getData")
.setProperty("viewClass", constant(CustomeJsonViews.class))
.marshal("customDataFormat").endRest()
.get("/allData").route()
.to("bean:daoService?method=getDatas")
.setProperty("viewClass", constant(CustomeJsonViews.class))
.marshal("customDataFormat").endRest();
}
}
CustomeDataFormat.java
public class CustomDataFormat implements DataFormat{
private ObjectMapper jacksonMapper;
public CustomDataFormat(){
jacksonMapper = new ObjectMapper();
}
@Override
public void marshal(Exchange exchange, Object obj, OutputStream stream) throws Exception {
Class view = (Class) exchange.getProperty("viewClass");
if (view != null)
{
ObjectWriter w = jacksonMapper.writerWithView(view);
w.writeValue(stream, obj);
}
else
stream.write(jacksonMapper.writeValueAsBytes(obj));
}
@Override
public Object unmarshal(Exchange exchange, InputStream stream) throws Exception {
return null;
}
}
一个完整的工作版本可以在这里找到: https://github.com/zwhitten/camel-rest-test
当去到URL,{主机}在Chrome/testApp /数据,例如响应来自通过为:
{
data: "Sherlock",
value: "Holmes",
count: 10
}
但是使用邮差浏览器插件的客户端返回:
"W3siZGF0YSI6ImRhdGE6OjAiLCJ2YWx1ZSI6InZhbHVlOjowIiwiY291bnQiOjB9LHsiZGF0YSI6ImRhdGE6OjEiLCJ2YWx1ZSI6InZhbHVlOjoxIiwiY291bnQiOjF9LHsiZGF0YSI6ImRhdGE6OjIiLCJ2YWx1ZSI6InZhbHVlOjoyIiwiY291bnQiOjJ9LHsiZGF0YSI6ImRhdGE6OjMiLCJ2YWx1ZSI6InZhbHVlOjozIiwiY291bnQiOjN9LHsiZGF0YSI6ImRhdGE6OjQiLCJ2YWx1ZSI6InZhbHVlOjo0IiwiY291bnQiOjR9LHsiZGF0YSI6ImRhdGE6OjUiLCJ2YWx1ZSI6InZhbHVlOjo1IiwiY291bnQiOjV9LHsiZGF0YSI6ImRhdGE6OjYiLCJ2YWx1ZSI6InZhbHVlOjo2IiwiY291bnQiOjZ9LHsiZGF0YSI6ImRhdGE6OjciLCJ2YWx1ZSI6InZhbHVlOjo3IiwiY291bnQiOjd9LHsiZGF0YSI6ImRhdGE6OjgiLCJ2YWx1ZSI6InZhbHVlOjo4IiwiY291bnQiOjh9LHsiZGF0YSI6ImRhdGE6OjkiLCJ2YWx1ZSI6InZhbHVlOjo5IiwiY291bnQiOjl9XQ=="
该问题似乎与REST绑定模式是“自动”并使用自定义编组器。 如果我将绑定模式设置为“json”,那么浏览器和客户端响应都会出现乱码。 如果我将绑定模式设置为“json”并绕过自定义编组器,则一切正常。 有没有办法将路由配置为使用自定义编组器并正确编码响应而不考虑客户端?