0

How can I upload a pdf with a http call to a server.

I am currently loading the pdf content to a variable and trying to send it with http:

byte[] pdfContent;

String output = "";

try {
    pdfContent = Files.readAllBytes(Paths.get("C:...//test.pdf"));
    url = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Type", "application/pdf");
    conn.setConnectTimeout(5000);
    conn.setReadTimeout(5000);
    conn.setRequestMethod("POST");
    
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(pdfContent.toString());
    wr.flush();
    wr.close();

The error I am getting is:

 Wrong content! The content of file 'test.pdf' does not match its presumed content type ('application/pdf').

What is the right way to send a pdf for upload? Is loading the binary content to a variable and writing it to the connection incorrect?

1
  • A PDF is not a string, and given pdfContent is a byte array, pdfContent.toString() will produce something like [B@12345, and finally, using a DataOutputStream is probably the wrong abstraction. Get a file input stream (Files.newInputStream) and call transferTo(conn.getOutputStream). Commented Mar 6, 2022 at 9:15

1 Answer 1

1

Have you tried wr.write(pdfContent); ? The write() function takes a byteArray as argument, so if the problem is caused by the conversion to String it might by solved that way

Sign up to request clarification or add additional context in comments.

1 Comment

Well yes, such a stupid mistake. Thanks for pointing out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.