簡體   English   中英

服務器返回 java.io.IOException:服務器返回 HTTP 響應代碼:URL 為 400

[英]server returns java.io.IOException: Server returned HTTP response code: 400 for URL

我正在嘗試調用記錄如下的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 響應代碼:URL 為 400:url

我試圖從郵遞員那里做同樣的事情並且它有效。 有任何想法嗎?

你發送什么作為數據? 至少你應該發送 -d {} 以獲取空數據或刪除 -d

如果它運行在 POSTMAN 中,您可以從中獲取相應的curl請求。 通過單擊Code並從可用選項中選擇cURL 在此處輸入圖片說明

我通過刪除Content-Type部分中的字符集解決了這個問題。 修改后這行看起來像這樣

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM