简体   繁体   中英

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

I am trying to call rest API which is documented like this

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

Here is my code sends http post. It works good with all http apis I used before but not for this.

        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;

I am getting an error

java.io.IOException: Server returned HTTP response code: 400 for URL: url

I tried to do the same from postman and it works. Any ideas?

What do you send as Data? at least you should send -d {} for empty data or remove -d

If it is running in POSTMAN, you can get the corresponding curl request from it. By clicking on Code and select cURL from available options. 在此处输入图片说明

I've solved it by removing charset in the Content-Type section. After modification this line looks like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM