如何在springboot中设置webservice响应的媒体类型?

时间:2017-07-21 08:42:27

标签: java web-services rest spring-boot

我创建了一个Web服务,我将从内部调用另一个Web服务。根据从内部打电话的响应媒体类型,我回复了我的真实回复。

但无论我做什么,所有响应都以JSON对象的形式返回。

我的网络服务类是;

@RestController
@RequestMapping("/changeservicemode")
public class ChangeServiceMode {

    @RequestMapping(method = RequestMethod.GET)
    public Response changeMode(@RequestHeader(value = "serviceUrl") String serviceUrl,
                               @RequestHeader(value = "serviceMode") String serviceMode) {

        IVirtualDocumentService docService = UtilsForSpring.getSingleBeanOfType(IVirtualDocumentService.class);
        VirtualDocument documentByUrl = docService.findDocumentByVirtualUrl(serviceUrl);

        String mediaType = MediaType.APPLICATION_XML;//I'll get media type from another response that will call above code in this point

        if (documentByUrl == null) {
            return Response.status(Status.NOT_FOUND).type(mediaType).entity("This url not found on DB!").build();
        }

        if (SimulationMode.LEARN.equalsIgnoreCase(serviceMode)) documentByUrl.setSimulationMode(SimulationMode.LEARN);
        if (SimulationMode.SIMULATE.equalsIgnoreCase(serviceMode)) documentByUrl.setSimulationMode(SimulationMode.SIMULATE);
        if (SimulationMode.STOP.equalsIgnoreCase(serviceMode)) documentByUrl.setSimulationMode(SimulationMode.STOP);

        docService.save(documentByUrl);
        String entity = "url: " + serviceUrl + ", mode: " + documentByUrl.getSimulationMode();

        return Response.status(Status.OK).entity(entity).type(mediaType).build();
    }
}

这是我的回复;

{
    "context": {
        "headers": {
            "Content-Type": [
                {
                    "type": "application",
                    "subtype": "xml",
                    "parameters": {},
                    "wildcardSubtype": false,
                    "wildcardType": false
                }
            ]
        },
        "entity": "url: http://localhost:8066/virtual/wsapi/personelvirtual/getallpersonels, mode: SIMULATE",
        "entityType": "java.lang.String",
        "entityAnnotations": [],
        "entityStream": {
            "closed": false,
            "committed": false
        },
        "length": -1,
        "language": null,
        "location": null,
        "lastModified": null,
                 .
                 .
                 .
                 . continue..

1 个答案:

答案 0 :(得分:1)

尝试指定此属性

produces = MediaType.APPLICATION_XML_VALUE

表示您为@RequestMapping方法设置的changeMode。根据{{​​3}},它应该做你想要的。