我尝试在我的spring启动项目中开发一个全局Web服务方法,并且我想根据请求的主体类型返回我的响应主体类型。无论我做什么,所有响应都返回json类型。
mydomain\user2
答案 0 :(得分:0)
我没找到我想要的东西。但我找到了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()));
}