【问题标题】:server returns java.io.IOException: Server returned HTTP response code: 400 for URL服务器返回 java.io.IOException:服务器返回 HTTP 响应代码:URL 为 400
【发布时间】:2020-01-27 14:39:38
【问题描述】:

我正在尝试调用像这样记录的 rest API

curl -X POST "https://url/api/v1/className/doSomething" -H "accept: application/json" -H "Authorization: Bearer token" -H "Content-Type: application/json" -d

这是我的代码发送 http 帖子。它适用于我之前使用的所有 http api,但不适用于此。

        String result = "";

        RequestProcess process = LogManager.getInstance().newProcess();
        process.setProcessName(url);
        process.setRequestContent(requestContent);

        ObjectMapper mapper = new ObjectMapper().registerModule(new Jdk8Module()).registerModule(new JavaTimeModule());


        String rawData = mapper.writeValueAsString(requestContent);

        String charset = "UTF-8";
        HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
        connection.setRequestProperty("User-Agent", USER_AGENT);
        connection.setRequestMethod("POST");

        try (OutputStream output = connection.getOutputStream()) {
            output.write(rawData.getBytes(charset));
        }

        InputStream inputStream = connection.getInputStream();
        result = StreamUtil.toString(inputStream);

        process.setResponseContent(result);
        LogManager.getInstance().endProcess(process);

        return result;

我收到一个错误

java.io.IOException:服务器返回 HTTP 响应代码:400 用于 URL:url

我尝试从邮递员那里做同样的事情并且它有效。有什么想法吗?

【问题讨论】:

  • 看起来您的 url 变量未正确初始化。您没有正确使用 curl 请求。请求中没有发布数据。因此,通过 null 有效负载,预期的异常仅为 400

标签: java http bad-request


【解决方案1】:

您将什么作为数据发送?至少您应该为空数据发送 -d {} 或删除 -d

【讨论】:

  • 我正在发送 json "{name: value}"
  • 你能不能提供方法签名,也可以用这个格式化程序来检查你的json数据:jsonformatter.curiousconcept.com
  • curl -d '{"name":"value"}' -H "accept: application/json" -H "Authorization: Bearer token" -H "Content-Type: application/json" -X POST url/api/v1/className/doSomething
【解决方案2】:

如果是在POSTMAN中运行,可以得到对应的curl 向它提出要求。通过单击Code 并从可用选项中选择cURL

【讨论】:

    【解决方案3】:

    我通过删除 Content-Type 部分中的 charset 解决了这个问题。 修改后这条线是这样的

    connection.setRequestProperty("Content-Type", "application/json");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      相关资源
      最近更新 更多