Apache CXF拦截器覆盖内容类型

时间:2013-12-02 15:03:01

标签: java web-services rest file-upload cxf

我有一个只接受带文件上传的POST请求的帖子服务:

@POST
@Path("uploadfile")
@Consumes({ "*/*" })
@Produces({ "*/*" })
public Response uploadFile(@Context UriInfo uri, @Context HttpHeaders httpHeaders, MultipartBody multipartBody);

如果前端客户端设置了“错误”的Content-Type,则会收到415响应错误。使用InInterceptor,我想将消息重新设置为MultipartBody:

@Override
public void handleMessage(Message message) throws Fault {
    System.out.println(message);
}

此处消息的类型为org.apache.cxf.message.XMLMessage。如何更改此选项,我的uploadFile方法将使用MultipartBody接受此请求?

PS: 前端客户端是未知的,无法更改,目前已经发送错误的内容类型......

我尝试过更改内容类型:

@Override
public void handleMessage(Message message) throws Fault {
    Map<String,String> map = (Map<String, String>)message.get(Message.PROTOCOL_HEADERS);
    message.put(Message.CONTENT_TYPE, "multipart/form-data");
    map.put("content-type", "[multipart/form-data]");
    message.put(Message.PROTOCOL_HEADERS, map);
}

但后来我得到了:

java.lang.RuntimeException: org.apache.cxf.interceptor.Fault: java.lang.String cannot be cast to java.util.List
    at org.apache.cxf.interceptor.AbstractFaultChainInitiatorObserver.onMessage(AbstractFaultChainInitiatorObserver.java:116)
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:333)
    at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)

1 个答案:

答案 0 :(得分:0)

好的,我发现我投错了......

Map<String,List> map = (Map<String, List>)message.get(Message.PROTOCOL_HEADERS);

Map<String,String> map = (Map<String, String>)message.get(Message.PROTOCOL_HEADERS);

所以现在它有效......

@Override
public void handleMessage(Message message) throws Fault {
    Map<String,List> map = (Map<String, List>)message.get(Message.PROTOCOL_HEADERS);
    message.put(Message.CONTENT_TYPE, "multipart/form-data");
    map.put("content-type", Collections.singletonList("multipart/form-data"));
    message.put(Message.PROTOCOL_HEADERS, map);
}