@Context
private MessageContext context;
public HttpServletRequest getRequest(){ HttpServletRequest request = (HttpServletRequest) context .get(AbstractHTTPDestination.HTTP_REQUEST); return request; } public String getUserName(HttpServletRequest request){ String userName = request.getHeader("userName"); return userName; }
通用的post 请求
@ApiOperation(value = "common data reception for 3rd party ") @PostMapping(value = "/receptionData") public Callable<Object> receptionData(HttpServletRequest request) { Callable<Object> result = new Callable<Object>() { @Override public Object call() throws Exception { log.info("enter into CommonDataReceptionFor3rdController class ==>getrequest methoed "); // get all header info log.info("==>>Request Content Type is {} ", request.getContentType()); Enumeration<String> requestHeader = request.getHeaderNames(); // Map<String, String[]> parameterMap = request.getParameterMap(); JSONObject parameterMap; ServletInputStream inputSteam = request.getInputStream(); if ("application/json".equalsIgnoreCase(request.getContentType())){//json
if(inputSteam==null){ return ResultUtils.resultFail(400,"请求无效" , null,"");} parameterMap = JSON.parseObject(IOUtils.toString(inputSteam,StandardCharsets.UTF_8.name())); }else{ //表单提交 parameterMap=ServletRequestUtil.getRequestParameter(request.getParameterMap()); } JSONObject header = new JSONObject(); while (requestHeader.hasMoreElements()) { String headerKey = requestHeader.nextElement().toString(); // System.err.println("headerKey="+headerKey+";value="+request.getHeader(headerKey)); header.put(headerKey, request.getHeader(headerKey)); } String platform = header.getString(HEADER_KEY_PLATFORM); if (StringUtils.isBlank(platform)) { String message = "request header must have headerKey:platform"; log.error("request header must have headerKey:platform"); log.error("the request data is :{}",message); return ResultUtils.resultFail(HttpServletResponse.SC_CREATED, message, null,platform); } try { String parameJson = (!parameterMap.isEmpty()) ? parameterMap.toJSONString() : ""; log.info("==>>Request Request Parameter is {} ", parameJson); dataDistributionService.dataDistribution(platform, parameJson); } catch (Exception e) { String message = "send data to kafka fail and exception :"+e; log.error("the request data is :{}",message); log.error("send data to kafka fail and exception :"+e); log.info("enter into CommonDataReceptionFor3rdController class ==>getrequest methoed "); return ResultUtils.resultFail(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message, null,platform); } log.info("save data to kafka success"); log.info("end the CommonDataReceptionFor3rdController class =>getrequest methoed "); return ResultUtils.resultOk("success", null,platform); } }; return result; }
@Slf4j public class ServletRequestUtil { public static JSONObject responseOk(String mesg) { JSONObject response = new JSONObject(); response.put(Constant.STATUS_CODE, Constant.SUCCESS_CODE); response.put(Constant.STATUS_MSG, "Process request successfully"); return response; } public static JSONObject getRequestParameter(Map<String, String[]> parameterMap) {//String[] 一般只有一个 log.debug("------- parameter -------"); JSONObject parameter = new JSONObject(); for (String key : parameterMap.keySet()) { for (int i = 0; i < parameterMap.get(key).length; i++) { log.debug("key=" + key + ";value=" + parameterMap.get(key)[i].toString()); parameter.put(key, parameterMap.get(key)[i].toString()); } } return parameter; } }
HttpServletRequest 获取body:
public String testpost(HttpServletRequest request) throws IOException { BufferedReader br = request.getReader(); String str, body = ""; while((str = br.readLine()) != null){ body += str; } System.err.println(body);}
使用post接口接收数据:
@Autowired private KafkaTemplate<String, String> kafkaTemplate; /** * Content-Type : application/x-www-form-urlencoded application/json * @param request * @return */ public static final String HEADER_KEY_PLATFORM = "from-platform"; public static final String CONTENT_TYPE_JSON="application/json"; public static final String CONTENT_TYPE_WWW_FORM_URLENCODED="application/x-www-form-urlencoded"; @ApiOperation(value = "dynamic data reception ") @RequestMapping(value = "/rest_reception", method = RequestMethod.POST) public Map reception(HttpServletRequest request) throws Exception { log.info(" ^^^^ start reception data ^^^^^ "); String contentType = request.getHeader("Content-Type")+""; log.info("content_type : {}" , contentType); Enumeration<String> headerNames = request.getHeaderNames(); // get header HashMap<String, String> headerMap = new HashMap<>(); while (headerNames.hasMoreElements()){ String headerName = headerNames.nextElement(); headerMap.put(headerName,request.getHeader(headerName)+""); } String platformTopic = headerMap.getOrDefault(HEADER_KEY_PLATFORM, null); System.err.println("platformTopic: "+ platformTopic); if(StringUtils.isBlank(platformTopic)){ return result("false","1","'"+HEADER_KEY_PLATFORM+"' header is blank "); } if(contentType.contains(CONTENT_TYPE_JSON)){ //get body String body = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8.name()); // kafkaTemplate.send("sea_new_api_test",body); kafkaTemplate.send(platformTopic,body); } else { // get form data Map<String, String[]> parameterMap = request.getParameterMap(); JSONObject lastData = new JSONObject(); lastData.put("path",request.getRequestURI()); lastData.put("data",getRequestParameter(parameterMap)); lastData.put("header",headerMap); System.err.println("req data is : " + JSON.toJSONString(lastData)); kafkaTemplate.send(platformTopic,lastData.toJSONString()); } log.info(" ^^^^ end reception data ^^^^^ "); return result("true","1","no"); } public static JSONObject getRequestParameter(Map<String, String[]> parameterMap) { JSONObject parameter = new JSONObject(); for (String key : parameterMap.keySet()) { for (int i = 0; i < parameterMap.get(key).length; i++) { log.debug("key=" + key + ";value=" + parameterMap.get(key)[i]); parameter.put(key, parameterMap.get(key)[i]); } } return parameter; } private JSONObject result(String success, String errorCode,String errorMsg){ return new JSONObject(){{ put("success",success); put("errorCode",errorCode); put("errorMsg",errorMsg); }}; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?