繁体   English   中英

如何在springboot中根据请求类型返回响应实体类型?

[英]How to return response entity type according to request type in springboot?

我尝试在我的Spring Boot项目中开发一个全局Web服务方法,并且我想根据请求正文类型返回响应正文类型。 无论我做什么,所有响应都将返回json类型。

@RestController
@RequestMapping(value = "/virtual/**", produces = {"application/json", "application/xml", "text/xml"}, consumes = MediaType.ALL_VALUE)
public class VirtualServiceGateway {

    private IVirtualDocumentService virtualService = UtilsForSpring.getSingleBeanOfType(IVirtualDocumentService.class);

    @RequestMapping(method = RequestMethod.GET)
    public Response requestGET(HttpServletRequest request, HttpServletResponse response) {


        IVirtualDocumentService docService = UtilsForSpring.getSingleBeanOfType(IVirtualDocumentService.class);
        docService.findDocumentByVirtualUrl(request.getRequestURL().toString());

        if (docService == null) {

            return Response.status(404).type(request.getContentType()).entity("There is no anything").build();
        }

        return Response.status(200).type(request.getContentType()).entity("ok!").build();

    }

我没有找到我想要的东西。 但是我找到了ResponseEntity,我们可以像下面这样使用它。 在这里,我可以根据请求/响应标头返回实体类型。

它对我有用,可能对某人有用

@RequestMapping(method = RequestMethod.GET)
    public ResponseEntity requestTEST(HttpServletRequest request, HttpServletResponse response) {

//        HttpGet httpGet = new HttpGet("http://www.webservicex.net/country.asmx/GetCountries"); // xml output format
        HttpGet httpGet = new HttpGet("http://services.groupkt.com/country/get/all");//json output format
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse res = null;
        StringBuilder resEntity = null;

        try {

            res = httpClient.execute(httpGet);
            resEntity = new StringBuilder();
            BufferedReader bf = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
            List<String> lines = IOUtils.readLines(bf);
            for (String line : lines) {
                resEntity.append(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        for (Header h : res.getAllHeaders()) {
            headers.add(h.getName(), h.getValue());
        }

        return new ResponseEntity(resEntity, headers, HttpStatus.valueOf(res.getStatusLine().getStatusCode()));
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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