Search code examples
javaapihttprequest

How to change Content type in HttpRequest?


Here is my code :

public static void main(String[] args) throws Exception {
    HttpClient client = HttpClient.newHttpClient();

    File file = new File("/home/xxxxxxxxx/Téléchargements/XxxXx");
    File[] files = file.listFiles();

    for (File f : files) {
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://exemple.demo.monapi.com/api/v5/submissions"))
        .POST(BodyPublishers.ofFile(FileSystems.getDefault().getPath(f.getAbsolutePath())))
        .header("Authorization", "Token c0198efc82c36812a6a32af0579a8332aa37f7a7")
        .build();
        
        HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
        System.out.println(response);
    }

}

The proble is that i get a 415 response because, by default content type is application/pdf and the supported content types for encoding the bodies of POST requests for my api are:

  • multipart/form-data (usually used when uploading files)
  • application/x-www-form-urlencode (for all remaining cases)

So how do i change the content type ?


Solution

  • You can add multiple headers by adding multiple .header("key", "value").

    Content type header is added along with Authorization header in below code

    HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://exemple.demo.monapi.com/api/v5/submissions"))
            .POST(BodyPublishers.ofFile(FileSystems.getDefault().getPath(f.getAbsolutePath())))
            .header("Authorization", "Token c0198efc82c36812a6a32af0579a8332aa37f7a7")
            .header("Content-Type", "multipart/form-data")
            .build();