[英]How to return response entity type according to request type in springboot?
I try to develop a global webservice method in my spring boot project and I want to return my response body type according to request body type. 我尝试在我的Spring Boot项目中开发一个全局Web服务方法,并且我想根据请求正文类型返回响应正文类型。 Whatever I do, all response return json type.
无论我做什么,所有响应都将返回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();
}
I didn't find something what I want. 我没有找到我想要的东西。 But I found ResponseEntity, and we can use it like below.
但是我找到了ResponseEntity,我们可以像下面这样使用它。 In there I can return entity type according to request/response headers.
在这里,我可以根据请求/响应标头返回实体类型。
It works for me, may be useful for somebody 它对我有用,可能对某人有用
@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.