一、定义postman请求
二、定义传递数据
三、定义HttpServletRequest接受json工具类
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson.JSONObject;
public class GetRequestJsonUtils {
public static JSONObject getRequestJsonObject(HttpServletRequest request) throws IOException {
String json = getRequestJsonString(request);
return JSONObject.parseObject(json);
}
public static String getRequestJsonString(HttpServletRequest request)
throws IOException {
String submitMehtod = request.getMethod();
if (submitMehtod.equals("GET")) {
return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\"");
} else {
return getRequestPostStr(request);
}
}
public static byte[] getRequestPostBytes(HttpServletRequest request)
throws IOException {
int contentLength = request.getContentLength();
if(contentLength<0){
return null;
}
byte buffer[] = new byte[contentLength];
for (int i = 0; i < contentLength;) {
int readlen = request.getInputStream().read(buffer, i,
contentLength - i);
if (readlen == -1) {
break;
}
i += readlen;
}
return buffer;
}
public static String getRequestPostStr(HttpServletRequest request)
throws IOException {
byte buffer[] = getRequestPostBytes(request);
String charEncoding = request.getCharacterEncoding();
if (charEncoding == null) {
charEncoding = "UTF-8";
}
return new String(buffer, charEncoding);
}
}
四、定义处理类,接收数据
@RestController
@RequestMapping("/switch")
public class SwitchEventController {
private static Logger log = LoggerFactory.getLogger(SwitchEventController.class);
@PostMapping("/event1")
public void event1(HttpServletRequest req) throws IOException{
log.info("cn.linkpower.controller.SwitchEventController.event");
log.info("接受到的map信息:\n{}",req.getAttribute("msgtype"));
log.info("获取到的json数据:{}",GetRequestJsonUtils.getRequestJsonObject(req));
}
}
五、测试请求数据