- 背景:有些冷门场景下,需要将json字符串以字符串的形式传递给后台接口,后台直接用String去读取,由于长度、包含特殊字符等原因,放在url、form字段都不太合适,或者需要繁琐的转换,急需一种能直接传递字符串的方式。
- 源码:
package com.yang.control.os.controller;
import org.RequestMapping;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
/**
* @description:
* @author: Yang JianXiong
* @since: 2022/12/6
*/
@Slf4j
@Controller
public class ZslnPosController {
@Resource
private TransactionService transactionService;
@Deprecated
@RequestMapping("/zsln/pos/transaction0")
public String transaction0(HttpServletRequest request) throws IOException {
// 1.从请求体中读取【输入字节流】
ServletInputStream inputStream = request.getInputStream();
// 2.将字节流转换为【字符流】
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
// 3.将字符流转为【缓冲字符流】
BufferedReader streamReader = new BufferedReader(inputStreamReader);
// 4.逐行读取
String line;
StringBuilder sb = new StringBuilder();
while ((line = streamReader.readLine()) != null) {
// 5.重新拼接每一行,还原字符串
sb.append(line);
}
// 6.下游逻辑
return this.transactionService.doPosTrade(sb.toString());
}
}
- 测试:
Postman中发起POST请求,长字符串放在body中以raw -> text的形式发送。