首页 > 解决方案 > 将一个 API 的 requestbody 发送到另一个 API

问题描述

这是我的代码

private static final String MEDIA_TYPE = "application/json";
    private static final String FORMAT = "UTF-8";
    private static String baseServiceUrl;
    private static String apiServiceUrl;
@RequestMapping("/")
    public ResponseEntity<?> getMessage() throws Exception {
        logger.info("Started");
        try {
            messageProcessor.getMessage("test service");
              // Read from request
            StringBuilder buffer = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            String data = buffer.toString();
            StringRequestEntity requestEntity = null;
            HttpClient httpclient = new HttpClient();
            int statusCode;
            logger.info("RequestBody"+data);
            baseServiceUrl="http://localhost:8080/services";
            apiServiceUrl="/services/rest/json";
            StringBuffer eventResponse = new StringBuffer();
            requestEntity = new StringRequestEntity(data, MEDIA_TYPE, FORMAT);
            PostMethod postMethod = new PostMethod(baseServiceUrl+apiServiceUrl);
            postMethod.setRequestEntity(requestEntity);
            statusCode = httpclient.executeMethod(postMethod);
            logger.info("Status code"+statusCode);

                } 
        catch (Exception ex) {
            logger.error("Exception occurs ", ex);
            return new ResponseEntity("Internal server error !!", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity("Successfully called the service!!", HttpStatus.OK);

    }

我想获取一个 API 的请求体并发送到另一个 API。json 是我的请求体。但在这段代码中,我得到的状态码为 400。谁能帮我解决这个问题

标签: javaspring-boot

解决方案


在您的代码中,您将请求正文作为字符串读取,您能否共享记录的请求正文。HTTP 响应代码 400 对应于 BAD 请求。因此,您尝试访问的端点可能不同,或者请求正文有问题。尝试/services从您的中删除apiServiceUrl以更正 url 路径。此外,由于您很可能将 json 作为请求正文,请尝试以下方法:

String json = "{"id":1,"name":"xxxx"}";
StringEntity entity = new StringEntity(json);
postMethod.setEntity(entity);
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");

确保您使用 BufferedReader 从请求中读取的字符串采用reader = request.getReader();适当的 json 格式。


推荐阅读