【问题标题】:Send the requestbody of one API to another API将一个 API 的 requestbody 发送到另一个 API
【发布时间】:2020-05-19 04:16:09
【问题描述】:

这是我的代码

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。谁能帮我解决这个问题

【问题讨论】:

  • 第二个 API 是同一个应用还是其他应用?
  • 不一样..另一个
  • 您是否检查过第二个网址是否可以通过直接调用而不通过身份验证?

标签: java spring-boot


【解决方案1】:

我认为您在网址中附加了 /services 两次。应该是这样的:

baseServiceUrl="http://localhost:8080/services"; apiServiceUrl="/rest/json";

【讨论】:

  • 我已经更正了..但又得到了 400 请求代码
  • 如果 apiServiceUrl 与 baseServiceUrl 属于不同的应用程序,您应该拥有 apiServiceUrl 的完整 url。如果您有权访问 API 代码,请检查路径。您是否还检查了来自浏览器的直接调用?
【解决方案2】:

在您的代码中,您将请求正文作为字符串读取,您能否分享记录的请求正文。HTTP 响应代码 400 对应于 BAD 请求。因此,您尝试访问的端点可能不同,或者请求正文有问题。尝试从 apiServiceUrl 中删除 /services 以更正 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 格式。

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 2020-02-09
    • 2020-04-26
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 2022-01-26
    相关资源
    最近更新 更多