发送请求contentType常见的几种类型及后台响应过程分析
前端使用post提交请求
1.1 content-type为 application/json
前端代码:
$.ajax({
type: 'post',
url:'postReq',
contentType:'application/json',
data:{
username:'admin',
content:'123123'
},
dataType:'json',
success:function (data) {
}
});
ajax请求中 content-type:application/json,这样也能在后台接受前台提交的数据,其实这个时候前端提交的数据是 json格式的字符串。
如果没有使用springmvc框架的情况下,只能采用传统的流的方式接收。
后台代码:
BufferedReader reader = null;
String line = "";
String xmlString = null;
try
{
reader = req.getReader();
StringBuffer inputString = new StringBuffer();
while ((line = reader.readLine()) != null)
{
inputString.append(line);
}
xmlString = inputString.toString();
}
catch (Exception e)
{
}
使用了sprigmvc 框架
@RequestBody String json
json 格式数据如下:
{
username:'admin',
content:'123123'
}
1.2 content-type为application/x-www-form-urlencoded
前端代码:
$.ajax({
type: 'post',
url:'postReq',
contentType:'application/x-www-form-urlencoded',
data:{
username:'admin',
content:'123123'
},
dataType:'json',
success:function (data) {
}
});
后台代码:
String username = req.getParameter("username");
String content = req.getParameter("content");
application/x-www-form-urlencoded: 窗体数据被编码为名称/值对。这是标准的编码格式。
原文链接:https://blog.csdn.net/java_xxxx/article/details/81205315
1.3 content-type为 multipart/form-data类型
前端代码:
<form id="userInfoForm" method="post"
action="postReq" enctype="multipart/form-data">
<fieldset>
<legend>用户基本信息</legend>
<p>姓名: <input type="text" name="username" id="username" /></p>
<p>
<label for="userPic">头像</label>
<input id="userPic" name="userPic" type="file">
</p>
<p>
<label for="userPic">资料</label>
<input id="ziliao" name="ziliao" type="file">
</p>
<p>
<input class="submit" type="submit" value="提交">
</p>
</fieldset>
</form>
搜狗浏览器显示的请求示例
multipart/form-data: 窗体数据被编码为一条消息,页上的每个控件对应消息中的一个部分。后台是无法像普通表单那样通过request.getParameter来获取用户提交的数据的,最好的方式是使用第三方的jar包获取数据,这方面有很多现成的成熟优秀的jar包。比如commons-fileupload-1.3.1.jar等,或者使用spring框架的DefaultMultipartHttpServletRequest。
if (ServletFileUpload.isMultipartContent(request))
{
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();//DiskFileItemFactory 创建FileItem 实例,并保存其内容在内存或者硬盘中
diskFileItemFactory.setSizeThreshold(1*1024*1024);//1m 超过这个阀值放入磁盘
diskFileItemFactory.setRepository(tempFile); // 不设置 默认存在为系统默认Temp文件路径,调用 System.getProperty("java.io.tmpdir") 获取
ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
fileUpload.setSizeMax(10*1024*1024);//设置所允许的最大的单个上传文件大小(对应一个FileItem对象)
FileItemIterator iter = fileUpload.getItemIterator(request);
try
{
while(iter.hasNext())
{
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField())
{
System.out.println("Form field " + name + " with value "
+ Streams.asString(stream) + " detected.");
}
else
{
System.out.println("File field " + name + " with file name "
+ item.getName() + " detected.");
String source = "E:/upload/" + item.getName();
File file1 = new File(source);
if(!file1.isDirectory())
{
try(FileOutputStream os = new FileOutputStream(file1);)
{
IOUtils.copy(stream, os);
}
}
System.out.println("wanchengle ");
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
使用spring 后台代码:
ServletFileUpload upload = new ServletFileUpload();
DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = req.getFileMap();
try
{
upload.getItemIterator(request);
} catch (Exception e)
{
throw new Exception("上传应用文件获取异常");
}
String flag = "";
for (String key : fileMap.keySet())
{
MultipartFile multipartFile = fileMap.get(key);
if (null == multipartFile)
{
continue;
}
if (multipartFile.getSize() > 2147483648L)
{
throw new Exception("文件大小不能超过2G");
}
String random = UUID.randomUUID().toString();
long start = System.currentTimeMillis();
flag = random + "-" + start;
String source = String.format("%s/%s/%s/", "temp", flag, multipartFile.getOriginalFilename());
File file = new File(source);
try
{
if (!file.exists())
{
file.getParentFile().mkdirs();
try (InputStream ins = multipartFile.getInputStream();
FileOutputStream os = new FileOutputStream(file))
{
IOUtils.copy(ins, os);
}
}
} catch (Exception e)
{
throw new Exception("应用临时文件创建异常");
}
break;
}
后台代码:
前端使用get提交请求
get请求的headers中没有content-type这个字段