@PostMapping( "/outbound")
public String createOutboundOrderApollo(@RequestBody OutboundCreateOrderDTO createOrderDTO) {
return JSON.toJSONString(createOrderDTO);
}
@PostMapping( "/test")
public CainiaoR test(HttpServletRequest request) {
// 二次封装request
CustomRequestWrapper requestWrapper = new CustomRequestWrapper(request);
return CainiaoR.success();
}
try {
String url = "推送消息url";
// 请求参数json字符串,格式如:"{\"name\":\"张三\"}" ,可通过构建对象后再转换成json字符串:JSONObject.toJSONString(obj)
String content = "请求参数json字符串";
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
requestHeaders.add("Content-Encoding", "UTF-8");
HttpEntity<String> entity = new HttpEntity<>(content, requestHeaders);
// 调用远程接口:httpClient restTemplate 等都可以使用,具体看个人习惯。
ResponseEntity response = restTemplate.postForEntity(url, entity, String.class);
JSONObject jsonObject = JSONObject.parseObject(response.getBody().toString());
if (jsonObject.containsKey("code") && jsonObject.getString("code").equals("SUCCESS")) {
log.info("推送成功");
}
} catch (Exception e) {
log.error(e.getMessage());
}
使用Postman模拟发送
接收数据
// 当请求参数有上传文件,3个及以下请求参数;
@PostMapping("/test")
public void test(String name, String id, MultipartFile file){
log.info("name:{}, id:{}, file: {}", name, id, file);
}
// 当请求参数有上传文件,3个以上请求参数,封装成请求对象,不能加@RequestBody注解;
@PostMapping("/test")
public void test(RequestDto reqDto){
log.info("name:{}, id:{}, file: {}", reqDto.getName(), reqDto.getIdcard(), reqDto.getFile());
}
try {
// 需要发送的文件流
MultipartFile multipartFile = null;
String url = "推送消息url";
// getStreamAsString 见 InputStream 提取;
String content = getStreamAsString(multipartFile.getInputStream());
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
requestHeaders.add("Content-Encoding", "UTF-8");
HttpEntity<String> entity = new HttpEntity<>(content, requestHeaders);
// 调用远程接口:httpClient restTemplate 等都可以使用,具体看个人习惯。
ResponseEntity response = restTemplate.postForEntity(url, entity, String.class);
JSONObject jsonObject = JSONObject.parseObject(response.getBody().toString());
if (jsonObject.containsKey("code") && jsonObject.getString("code").equals("SUCCESS")) {
log.info("推送成功");
}
} catch (Exception e) {
log.error(e.getMessage());
}
@PostMapping( "/test")
public void test(String name, String id){
log.info("name:{}, id:{}", name, id);
}
@PostMapping("/test")
public void test(RequestDto reqDto){
log.info("name:{}, id:{}, file: {}", reqDto.getName(), reqDto.getIdcard(), reqDto.getFile());
}
public void test() {
try {
// params 需要发送的数据
Map<String, String> params = new HashMap<>();
String url = "推送消息url";
String content = buildQuery(params, "UTF-8");;
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
requestHeaders.add("Content-Encoding", "UTF-8");
HttpEntity<String> entity = new HttpEntity<>(content, requestHeaders);
// 调用远程接口:httpClient restTemplate 等都可以使用,具体看个人习惯。
ResponseEntity response = restTemplate.postForEntity(url, entity, String.class);
JSONObject jsonObject = JSONObject.parseObject(response.getBody().toString());
if (jsonObject.containsKey("code") && jsonObject.getString("code").equals("SUCCESS")) {
log.info("推送成功");
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
public static String buildQuery(Map<String, String> params, String charset) throws IOException {
if (params == null || params.isEmpty()) {
return null;
}
StringBuilder query = new StringBuilder();
Set<Map.Entry<String, String>> entries = params.entrySet();
boolean hasParam = false;
for (Map.Entry<String, String> entry : entries) {
String name = entry.getKey();
String value = entry.getValue();
// 忽略参数名或参数值为空的参数
if (StringUtils.areNotEmpty(name, value)) {
if (hasParam) {
query.append("&");
} else {
hasParam = true;
}
query.append(name).append("=").append(URLEncoder.encode(value, charset));
}
}
return query.toString();
}
private final byte[] body;
private String bodyString;
@SneakyThrows
private byte[] initInputStream(HttpServletRequest request) {
// getStreamAsString 见 InputStream 提取;
this.bodyString = getStreamAsString(request.getInputStream());
return bodyString.getBytes(StandardCharsets.UTF_8);
}
// 获取请求头信息
private static Map<String, String> initHeaders(HttpServletRequest request) {
Map<String, String> headers = new HashMap<>();
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String header = request.getHeader(headerName);
headers.put(headerName, header);
}
return headers;
}
// 获取
private Map<String, String[]> initParameters(HttpServletRequest request) {
Map<String, String[]> parameterMap = new HashMap<>();
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
String[] parameterValues = request.getParameterValues(paramName);
parameterMap.put(paramName, parameterValues);
}
return parameterMap;
}
private static String getStreamAsString(InputStream stream) throws IOException {
try {
Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
StringBuilder response = new StringBuilder();
final char[] buff = new char[1024];
int read = 0;
while ((read = reader.read(buff)) > 0) {
response.append(buff, 0, read);
}
return response.toString();
} finally {
if (stream != null) {
stream.close();
}
}
}
/**
* @Author: carroll
* @Date: 2023-12-22
* @Since: 1.0
*
* 自定义HttpServletRequest 实现参数重复读取,请求头写入,请求头获取等功能
* 满足各种平台各种数据数据格式传输和租户信息配置
*/
public class CustomRequestWrapper extends HttpServletRequestWrapper {
private final Map<String, String[]> params;//定义参数集合
private Map<String, String> headerMap;
private final RedisUtils redisUtils;
// 将request 里面的东西 缓存到这个数组里面
private final byte[] body;
private String bodyString;
public CustomRequestWrapper(HttpServletRequest request, RedisUtils redisUtils) {
super(request);
this.params = initParameters(request);
this.headerMap = initHeaders(request);
this.redisUtils = redisUtils;
this.body = initInputStream(request);
getRequestOpenid();
}
@SneakyThrows
private byte[] initInputStream(HttpServletRequest request) {
this.bodyString = getStreamAsString(request.getInputStream());
return bodyString.getBytes(StandardCharsets.UTF_8);
}
private void getRequestOpenid() {
String openid = "";
// 可以获取外部推送各种接口请求头中的数据 然后将对应的货主等信息放到请求头中
String partner_code = getParameter("partner_code");
if (CharSequenceUtil.isNotBlank(partner_code)) {
openid = partner_code;
}
Object obj = redisUtils.get(GlobalConstants.OPENID + openid);
if (Objects.isNull(obj)) {
throw new BizException("未获取到有效请求头数据");
}
QiMenOwnerCache ownerCache = JSONUtil.toBean(obj.toString(), QiMenOwnerCache.class);
initOwnerInfo(String.valueOf(ownerCache.getTenantId()), String.valueOf(ownerCache.getWarehouseId()), String.valueOf(ownerCache.getOwnerId()));
}
private Map<String, String[]> initParameters(HttpServletRequest request) {
Map<String, String[]> parameterMap = new HashMap<>();
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
String[] parameterValues = request.getParameterValues(paramName);
parameterMap.put(paramName, parameterValues);
}
return parameterMap;
}
public void initOwnerInfo(String tenantId,String warehouseId,String ownerId) {
headerMap.put(SecurityConstants.TENANT_ID_HEADER, tenantId);
headerMap.put(SecurityConstants.WAREHOUSE_ID_HEADER, warehouseId);
headerMap.put(SecurityConstants.OWNER_ID_HEADER, ownerId);
}
private static Map<String, String> initHeaders(HttpServletRequest request) {
Map<String, String> headers = new HashMap<>();
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String header = request.getHeader(headerName);
headers.put(headerName, header);
}
return headers;
}
@Override
public String getParameter(String name) {
String[] vs = params.get(name);
if (vs == null || vs.length < 1)
return null;
return vs[0];
}
@Override
public Enumeration<String> getParameterNames() {
return Collections.enumeration(params.keySet());
}
@Override
public String[] getParameterValues(String name) {
String[] vs = params.get(name);
if (vs == null || vs.length < 1)
return new String[0];
return vs;
}
@Override
public String getHeader(String name) {
return this.headerMap.getOrDefault(name, headerMap.get(name.toLowerCase()));
}
@Override
public Enumeration<String> getHeaderNames() {
return Collections.enumeration(this.headerMap.keySet());
}
public String getBodyString() {
return this.bodyString;
}
@Override
public BufferedReader getReader() {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() {
final ByteArrayInputStream innerBAIS = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() {
return innerBAIS.read();
}
};
}
private static String getStreamAsString(InputStream stream) throws IOException {
try {
Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
StringBuilder response = new StringBuilder();
final char[] buff = new char[1024];
int read = 0;
while ((read = reader.read(buff)) > 0) {
response.append(buff, 0, read);
}
return response.toString();
} finally {
if (stream != null) {
stream.close();
}
}
}
}
你知道的越多,你不知道的越多。