使用 Chrome 浏览器的 REST Client 插件 YARC 进行测试的时候,发现没毛病正常接受 post 请求体,但使用 linux 再带的 curl 请求时就是获取不到 post 请求体的内容,一度怀疑是 curl 的毛病尝试写程序调用发现确实有问题, receive.jsp 代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.io.*" %> <%@ page import="java.util.*" %> <%@ page import="java.text.SimpleDateFormat" %> <% int contentLength = request.getContentLength(); System.out.println("ContentLength: " + contentLength); String basePath = application.getRealPath("/"); File dataDir = new File(basePath + "data/"); if(!dataDir.exists()){ dataDir.mkdir(); System.out.println("创建 data 目录"); } PrintWriter pw = null; try { String id = request.getParameter("id"); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String fileName = String.format("%s_%s.txt", id, sdf.format(new Date())); File file = new File(dataDir, fileName); pw = new PrintWriter(new FileOutputStream(file,true)); String str = "",temp = ""; BufferedReader br = request.getReader(); while((temp = br.readLine()) != null){ System.out.println(" temp: " + temp); str += temp; } pw.println(str); pw.flush(); response.getWriter().write("0|success"); } catch (Exception e) { response.getWriter().write("1|fail"); }finally{ if(null != pw){ pw.close(); } } %>
网上找了好久文章帖子有说法是 “获取body参数,需要在request.getParameter()方法之前调用(如果有需要取QueryString参数的话),因为一旦调用了getParameter()方法之后,再通过IO流的方式获取body参数就失效了”。
修改测试了一下,好啦,果然是这个问题,修改后的代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.io.*" %> <%@ page import="java.util.*" %> <%@ page import="java.text.SimpleDateFormat" %> <% int contentLength = request.getContentLength(); System.out.println("ContentLength: " + contentLength); String basePath = application.getRealPath("/"); File dataDir = new File(basePath + "data/"); if(!dataDir.exists()){ dataDir.mkdir(); System.out.println("创建 data 目录"); } PrintWriter pw = null; try { String str = "",temp = ""; BufferedReader br = request.getReader(); while((temp = br.readLine()) != null){ System.out.println(" temp: " + temp); str += temp; } String id = request.getParameter("id"); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String fileName = String.format("%s_%s.txt", id, sdf.format(new Date())); File file = new File(dataDir, fileName); pw = new PrintWriter(new FileOutputStream(file,true)); pw.println(str); pw.flush(); response.getWriter().write("0|success"); } catch (Exception e) { response.getWriter().write("1|fail"); }finally{ if(null != pw){ pw.close(); } } %>
curl post 请求示例:
curl -d 'curl请求体' http://localhost:8080/test/receive.jsp?id=test_err # 上面请求时,写文件中文乱码,添加如下请求头解决中文写文件乱码问题 curl -H 'Content-Type: application/json;charset=utf-8' -d 'curl请求体' http://localhost:8080/test/receive.jsp?id=test_err