WSO2 EI调用HTTP接口遇JSON解析错误,如何处理多内容类型?
WSO2 EI调用HTTP端点解析text/json响应报错
调用时出现错误:
Unexpected character '{' (code 123) in prolog; expected '<'
直接通过curl调用该端点的结果:
* Trying IP:PORT... * TCP_NODELAY set * Connected to ... > POST /source.html HTTP/1.1 > Host: IP:PORT > User-Agent: curl/7.68.0 > Accept: */* > Content-Type: application/x-www-form-urlencoded > Content-Length: 63 > * upload completely sent off: 63 out of 63 bytes * Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < Server: Mule EE Core Extensions/3.9.5-20230823 < Set-Cookie: Stick=R2583989947; Domain=trionline.iic.local; Path=/ < Transfer-Encoding: chunked < Content-Type: text/json; charset=utf-8 < Date: Mon, 01 Jan 2024 10:19:52 GMT < Keep-Alive: false < http.version: HTTP/1.1 < X-Powered-By: Servlet/2.5 JSP/2.1 < http.status: 200 < http.request: .../resource.html < http.headers: {Transfer-Encoding=chunked, Keep-Alive=false, Connection=false, Set-Cookie= [Lorg.apache.commons.httpclient.Cookie;@1f6ae621, Date=Mon, 01 Jan 2024 10:19:52 GMT, X- Powered-By=Servlet/2.5 JSP/2.1, Content-Type=text/json; charset=utf-8} < http.method: POST < http.query.params: {} < http.query.string: < Connection: close < * Closing connection 0{"token":"..."}
报错核心原因:WSO2 EI默认对未识别的内容类型按XML解析,而该端点返回的text/json未被EI识别为JSON类型,导致解析JSON起始符{时触发XML解析错误。以下是处理不同内容类型的具体方案:
解决方案
1. 全局配置添加text/json识别
编辑EI安装目录下的repository/conf/synapse.properties,找到synapse.commons.json.input.types属性,将text/json加入JSON类型列表:
synapse.commons.json.input.types=application/json,text/json
此配置让EI自动把text/json响应当作JSON处理,无需额外转换。
2. 配置消息构建器与格式化器
在repository/conf/message-builders.xml中添加text/json对应的JSON解析器:
<messageBuilder contentType="text/json" class="org.apache.synapse.commons.json.JsonStreamBuilder"/>
在repository/conf/message-formatters.xml中添加对应的输出格式化器:
<messageFormatter contentType="text/json" class="org.apache.synapse.commons.json.JsonStreamFormatter"/>
确保EI能正确解析和输出text/json类型的消息。
3. 通过序列动态转换内容类型
若无法修改全局配置,可在API/代理服务的响应流(outFlow)中添加序列,动态将text/json替换为application/json:
<sequence xmlns="http://ws.apache.org/ns/synapse" name="TextJsonConverter"> <property name="transport_content_type" expression="get-property('transport', 'Content-Type')" scope="default"/> <filter source="$ctx:transport_content_type" regex="text/json"> <then> <property name="CONTENT_TYPE" value="application/json" scope="transport"/> </then> </filter> </sequence>
将该序列关联到API的outFlow:
<api xmlns="http://ws.apache.org/ns/synapse" name="YourAPI" context="/your-api"> <outFlow> <sequence key="TextJsonConverter"/> <send/> </outFlow> <!-- 其他API配置 --> </api>
4. 端点级别强制指定消息类型
在HTTP端点配置中,强制指定响应按JSON处理:
<endpoint xmlns="http://ws.apache.org/ns/synapse" name="TargetEndpoint"> <http uri="http://IP:PORT/source.html"> <property name="messageType" value="application/json" scope="axis2"/> </http> </endpoint>
此配置忽略原始Content-Type头,直接按JSON解析响应。
内容的提问来源于stack exchange,提问作者behzad
相关产品推荐
相关产品推荐

