@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);
        }};
    }

 

posted on 2018-11-30 15:25  lshan  阅读(934)  评论(0编辑  收藏  举报