Home > OS >  Send application/pdf content with http call
Send application/pdf content with http call

Time:03-03

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?

CodePudding user response:

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

  • Related