请有人给我一个关于我下面问题的提示。谢谢。
我们在请求中使用内容类型“application/x-www-form-urlencoded”获取来自服务器的 XML 内容。
我们尝试在 Groovy 中以 XML 形式读取请求,并收到以下错误。 [ fatal error ] :1:1:文件过早结束。 2015-11-16 17:15:26,777 错误。GrailsExceptionResolver SAXParseException 处理请求时发生:[POST]/games/api/v1/endpoint 文件过早结束。堆栈跟踪如下:
不幸的是,我们无法更改服务器上的内容类型。
我们尝试创建一个代理来获取来自服务器的请求,并将内容类型更改为“application/xml”,然后重定向到实际端点,以便我们可以正确读取 XML。
@Controller
@EnableAutoConfiguration
public class SampleController {
@RequestMapping(value = "/e2-proxy", method = RequestMethod.POST)
String home(HttpServletRequest request) {
InputStreamEntity requestEntity = null;
try {
requestEntity = new InputStreamEntity(request.getInputStream(),ContentType.create("text/xml", Consts.UTF_8));
} catch (IOException e1) {
e1.printStackTrace();
}
HttpPost httppost = new HttpPost("URL");
httppost.setEntity(requestEntity);
requestEntity.setChunked(true);
requestEntity.setContentType("text/xml");
httppost.setHeader(HTTP.CONTENT_TYPE, "text/xml");
HttpClient client = HttpClients.createDefault();
try {
client.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
使用 Apache HttpClient 进行请求重定向。但是,更改内容类型后我们仍然无法读取 XML。
请帮助验证解决方案,了解肯定出了什么问题,并提出任何替代方案。
最佳答案
请尝试这个,您需要添加字符集。
httppost.setHeader(HTTP.CONTENT_TYPE,"text/xml; charset=\"utf-8\"");
关于java - 更改请求的 Content-Type 以处理使用 application/x-www-form-urlencoded 发送的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33752468/