简体   繁体   中英

Apache CXF interceptor override content-type

I have a post service that only accepts POST requests with file upload:

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

If a front end client has set "wrong" Content-Type it gets 415 response error. With InInterceptor I would like to re-set the message to MultipartBody:

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

Here Message is type org.apache.cxf.message.XMLMessage . How do I change this that my uploadFile method will accept this request with MultipartBody?

PS: Front-end clients are unknown and cannot be changed and currently already are sending wrong content-types...

I have tried just changing the Content-type:

@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);
}

But then I get:

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)

Ok, I found out that I had casting wrong...

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

Not

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

So now it works...

@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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM