如何在Apache Camel的Undertow路由中获取原始POST请求体?
解决Apache Camel Undertow端点无Content-Type时获取原始请求体的问题
问题场景
使用Apache Camel搭建HTTP文件接收端点,路由配置如下:
<route id="example-inbox"> <from uri="undertow:http://localhost:8080/example-inbox" /> <to uri="file:inbox/" /> </route>
当携带Content-Type: text/plain头发起POST请求时,文件写入正常:
curl -i -X POST localhost:8080/example-inbox \ -H "Content-Type: text/plain" \ --data 'hello'
但省略Content-Type头时,会抛出类型转换异常:
org.apache.camel.InvalidPayloadException: No body available of type: java.io.InputStream but has type: java.util.HashMap on: Message[98010B440702286-0000000000000000]. Caused by: No type converter available to convert from type: java.util.HashMap to the required type: java.io.InputStream. Exchange[98010B440702286-0000000000000000]. Caused by: [org.apache.camel.NoTypeConversionAvailableException - No type converter available to convert from type: java.util.HashMap to the required type: java.io.InputStream]
尝试添加<convertBodyTo type="java.lang.String" />转换时,会将解析后的HashMap转为字符串{hello=},无法得到原始请求体。
问题原因
Undertow组件默认会将无Content-Type头的请求视为application/x-www-form-urlencoded格式,自动解析请求体为HashMap,导致Camel无法将其转换为InputStream写入文件。
解决方案
在Undertow端点的URI中添加rawPayload=true参数,强制跳过表单解析逻辑,直接获取原始请求体的字节流:
<route id="example-inbox"> <from uri="undertow:http://localhost:8080/example-inbox?rawPayload=true" /> <to uri="file:inbox/" /> </route>
此时无需携带Content-Type头,直接发起POST请求即可将原始内容写入文件:
curl -i -X POST localhost:8080/example-inbox --data 'hello'
该参数会让Undertow始终返回原始的请求体字节流,不受Content-Type头的影响,完美匹配直接写入文件的需求。
内容的提问来源于stack exchange,提问作者sba
相关产品推荐
相关产品推荐

