前端传参中,请求头中的 Content-Type 会有多种形式,这里只列举两种
- application/json
- application/x-www-form-urlencoded
同一个接口,来接收不同的 Content-Type 类型,代码如下。通过判断不同的Content-Type,使用不同的方式读取数据。 请求是 Post 请求:
@PostMapping("Pay")
@ApiOperation(value = "支付接口", response = ScanPayPassivityVo.class)
@ApiResponses({
@ApiResponse(code = 1000, message = "成功"),
@ApiResponse(code = 5000, message = "系统异常"),
@ApiResponse(code = 2004, message = "非法参数(因参数引起的错误)"),
@ApiResponse(code = 1017, message = "查询数据为空")
})
public ApiResultVo Pay( HttpServletRequest httpServletRequest) throws IOException {
String contentType = httpServletRequest.getHeader("Content-Type");
ScanPayPassivityRequest reqEntity = new ScanPayPassivityRequest();
if(contentType.equals("application/json")){
String str = ReadAsChars(httpServletRequest);
reqEntity = JSONObject.parseObject(str,ScanPayPassivityRequest.class);
}else if(contentType.equals("application/x-www-form-urlencoded")){
reqEntity.setQrCode(httpServletRequest.getParameter("qrCode"));
reqEntity.setScanPayType(null == httpServletRequest.getParameter("scanPayType") ? null: Integer.valueOf(httpServletRequest.getParameter("scanPayType")));
reqEntity.setPayAmount(null == httpServletRequest.getParameter("payAmount") ? null : new BigDecimal(httpServletRequest.getParameter("payAmount")));
reqEntity.setMerchantId(null == httpServletRequest.getParameter("merchantId") ? null : Long.valueOf(httpServletRequest.getParameter("merchantId")));
reqEntity.setOrderId(httpServletRequest.getParameter("orderId"));
reqEntity.setDeviceId(httpServletRequest.getParameter("deviceId"));
}
return xxservice.Pay(reqEntity);
}
//application/json 方式读取数据
public static String ReadAsChars(HttpServletRequest request)
{
BufferedReader br = null;
StringBuilder sb = new StringBuilder("");
try {
br = request.getReader();
String str;
while ((str = br.readLine()) != null)
{
sb.append(str);
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
} finally {
if (null != br) {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
application/x-www-form-urlencoded 格式 postman发送形式
application/json格式 postman发送形式