【问题标题】:How to pass an unknown incoming requestParam to a post in spring boot?如何将未知的传入 requestParam 传递给 Spring Boot 中的帖子?
【发布时间】:2021-07-15 18:21:36
【问题描述】:

在我的 spring boot 项目中,我试图以这种方式拦截一个 rest api 帖子:

休息控制器: @Rest 控制器 @RequestMapping("/") 公共类 FourStoreControllerInterface {

        @ApiOperation(value = "Manage Multiple 4Store Post")
        @ApiResponses(value = { @ApiResponse(code = 401, message = "Unauthorized"),
                @ApiResponse(code = 403, message = "Forbidden") })
        @PostMapping("**")
        public ResponseEntity<?> manageMultiplePost4StoreWithRestTemplate(
                @RequestParam @ApiParam(hidden = true) Map<String, String> allParams) throws Exception{
            final String methodName = "manageMultiplePost4StoreWithRestTemplate()";
            try {
    
                startLog(methodName);
    
                return fourStoreService.managePostEndpointsWithRestTemplate(allParams);
    
            } catch (final Exception e) {
                this.errorLog(methodName, e);
                throw e;
            } finally {
                endLog(methodName);
            }
    }

}

服务:

@ResponseBody
public ResponseEntity<?> managePostEndpointsWithRestTemplate(Map<String, String> allParams) {
    final String methodName = "managePostEndpointsWithRestTemplate(Map<String, String> allParams, JSONObject jsonParams)";
    try {
        startLog(methodName);
        return managePost(allParams);
    } catch (Exception e) {
        logger.error(e.getMessage());
        throw e;
    } finally {
        endLog(methodName);
    }
}

managePost(AbstractService 中实现的方法):

public ResponseEntity<?> managePost(Map<String, String> allParams) {
        try {
            try {

            logger.debug("I AM HERE WITH MAP");

            // REQUEST 1
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                    .getRequest();

            Route routeConfiguration = findRootPosts(request);
            if (routeConfiguration != null) {
                String url = routeConfiguration.getDestination().getProtocol()
                        + routeConfiguration.getDestination().getIp() + ":"
                        + routeConfiguration.getDestination().getPort() + request.getRequestURI();

                boolean first = true;
                for (String key : allParams.keySet()) {
                    logger.debug("OLD ALL PARAMETERS : {} ", key + "=" + allParams.get(key));
                }

                HttpHeaders headers = new HttpHeaders();
                headers.setBasicAuth(routeConfiguration.getDestination().getUsername(),
                        routeConfiguration.getDestination().getPassword());

                for (String headersName : Collections.list(request.getHeaderNames())) {
                    List<String> headersValue = Collections.list(request.getHeaders(headersName));
                    headers.put(headersName, headersValue);
                    logger.debug(" REQUEST 1 HEADERS : {} = {} ", headersName, headersValue);
                }

                for (Cookie c : request.getCookies()) {
                    logger.debug(" REQUEST 1 COOKIES : {} = {} ", c.getName(), c.getValue());
                }

                MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
//                  map.putAll(headers);
                    for (String key : allParams.keySet()) {
                        map.put(key, Arrays.asList(allParams.get(key)));
                    }
                    logger.debug("MAP OF PARAMETERS : {} ", map);

                // REQUEST 2
                HttpEntity<MultiValueMap<String, String>> request2;
                if (allParams != null && !allParams.isEmpty())
                    request2 = new HttpEntity<MultiValueMap<String, String>>(map, headers);
                else
                    request2 = new HttpEntity(headers);

                logger.debug("BODY REQUEST 2: {} ", request2.getBody());

                if (url.startsWith("https")) {
                    restTemplate = getRestTemplateForSelfSsl();
                } else {
//                      restTemplate = new RestTemplate();
                    }
                    logger.debug("URL POST: {} ", url);

                UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(url).build(true);
                ResponseEntity<?> response;
                if (xssResponseFilter) {
                    response = restTemplate.exchange(new URI(uriComponents.toUriString()), HttpMethod.POST,
                            request2, String.class);
                } else {
                    response = restTemplate.exchange(new URI(uriComponents.toUriString()), HttpMethod.POST,
                            request2, byte[].class);
                }

                HttpStatus statusCode = response.getStatusCode();
                logger.debug("STATUS POST: {} ", statusCode);

                HttpHeaders responseHeaders = response.getHeaders();
                logger.debug("RESPONSE HEADERS : {} ", responseHeaders);

                logger.debug("RESPONSE POST: {} ", response);

                if (xssResponseFilter) {
                    response = sanitizeResponseBody((ResponseEntity<String>) response);
                }
                return response;
            }
        } catch (HttpStatusCodeException e) {
            logger.error(e.getMessage());
            return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsByteArray());
        }
    } catch (Exception e) {
        logger.error(e.getMessage());
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
    }
    return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Not valid route found");
}

使用一些 POST 我没有问题,实际上我得到了 200,而且我还可以看到我在输入中传递的地图中存在的所有参数......使用其他 POST 我得到错误 400 BAD REQUEST,我请注意,输入参数的映射给我打印空白。我该如何解决这个问题? 在我看来,问题在于入口处我发现自己是一张空白地图……在这些情况下我该怎么办?

【问题讨论】:

    标签: java spring post resttemplate


    【解决方案1】:

    在休息控制器类中添加@RestController注解。

    【讨论】:

    • 实际上这个注释已经在我的项目中......我忘了在问题中写它......无论如何,很好地调查浏览器我注意到帖子需要一个作为 JSON 的正文...但我总是有地图传入空的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 2018-11-03
    相关资源
    最近更新 更多