例如: Content-Type: text/html;charset=utf-8;
常见的媒体格式类型如下:
以application开头的媒体格式类型:
另外一种常见的媒体格式是上传文件之时使用的:
以上就是我们在日常的开发中,经常会用到的若干content-type的内容格式。
最近项目开发对接接口,那边发送http post请求(
已知是xml数据,类似
抓包显示,"Content-Type" 是 "application/x-www-form-urlencoded;charset=GBK",
在body里用如下方式获取数据:(该方式获取不到数据)
public String parserRequest() {
HttpServletRequest request = ServletActionContext.getRequest();
StringBuffer sb = null;
InputStream in = null;
BufferedReader br = null;
try {
in = request.getInputStream();
br = new BufferedReader(new InputStreamReader(in, "utf-8"));
sb = new StringBuffer();
String s = "";
while ((s = br.readLine()) != null) {
sb.append(s);
}
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage(), e);
} finally {
try {
if (br != null) {
br.close();
}
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
String xml = sb.toString();
if (xml != null && !"".equals(xml)) {
logger.info("报文response xml = " + xml);
}
return xml;
}
**这种方式可以:(觉得很怪。。。想着一般post请求,都body体读取流数据
**"Content-Type" = "application/x-www-form-urlencoded 这种格式要特别注意)
public String parserRequest() {
HttpServletRequest request = ServletActionContext.getRequest();
String reqXml = null;
try {
Map
StringBuffer xmlBuf = new StringBuffer();
for (Map.Entry
logger.info("返回的报文 key=" + m.getKey() + " Value[0]="
+ m.getValue()[0]);
//打印出来的key=
xmlBuf.append(m.getKey());
xmlBuf.append("=");
xmlBuf.append(m.getValue()[0]);
}
reqXml = xmlBuf.toString();
} catch (Exception e) {
logger.error("Exception" + e.getMessage(), e);
}
if (reqXml != null && !"".equals(reqXml)) {
logger.info("报文response reqXml = " + reqXml);
}
return reqXml;
}
原因如下:
在servlet规范3.1.1节里
1. The request is an HTTP or HTTPS request.
2. The HTTP method is POST.
3. The content type is application/x-www-form-urlencoded.
4. The servlet has made an initial call of any of the getParameter family of methods on the request object.
If the conditions are met, post form data will no longer be available for reading directly from the request object’s input stream.
在tomcat的Request.parseParameters方法里,对于application/x-www-form-urlencoded
是有做判断的,对这种编码会去解析body里的数据,填充到parameters里,所以后续想再通过流的方式读取body是读不到的(除非你没有触发过getParameter相关的方法)。
tomcat源码。。。待续。。。。。。。。。。。。。
另外,看了下 org.apache.commons.httpclient.HttpClient 的源码 ,设置body体数据编码格式,
postMethod.setRequestEntity(new StringRequestEntity(body,contentType, charSet));
当"Content-Type" = "application/x-www-form-urlencoded;charset=GBK"
charSet="UTF-8" 两个参数都传入时,到底用哪个编码?
由源码看来,以第二个参数 charSet 为准。****
源码如下:
未完待续。。。。。。
手机扫一扫
移动阅读更方便
你可能感兴趣的文章