bashapipostmime-typescontent-length

How to calculate Content-Length of a POST request to API in bash?


I am using bash script to send POST request to RESTful API.

The Content-Length is incorrect. Please help to see if I calculate it wrongly.

Does the POST request add some more bytes inside my request?

Request body (This is exactly the same body except that the info are masked with X, x or 0):

--1234
Content-Disposition: form-data; name="xxxxx"

XXX-XX
--1234
Content-Disposition: form-data; name="xxx_xxxx"

XXXX00000000Xx0000000000000000000XX00.pdf
--1234
Content-Disposition: form-data; name="xxx_xx"

XXXX00000000Xx0000000000000000000XX00
--1234--

I set it 271 and it API captured the following:

--1234
Content-Disposition: form-data; name="xxxxx"

XXX-XX
--1234
Content-Disposition: form-data; name="xxx_xxxx"

XXXX00000000Xx0000000000000000000XX00.pdf
--1234
Content-Disposition: form-data; name="xxx_xx"

XXXX00000000Xx0000000000000000000XX00


Solution

  • My suggestion is not to reinvent the wheel. Tools like cURL create those multipart/form-data requests in a convenient and reliable manner, and there's no need to calculate the Content-Length on your own:

    Here is how you specify your request as a cURL command:

    curl \
    --request POST \
    --header 'Content-Type: multipart/form-data' \
    --form 'xxxxx=XXX-XX' \
    --form 'xxx_xxxx=XXXX00000000Xx0000000000000000000XX00.pdf' \
    --form 'xxx_xx=XXXX00000000Xx0000000000000000000XX00' \
    $'http://example.com/'
    

    And here's how your resulting raw request may look. Note that cURL has included the correct Content-Length header:

    POST / HTTP/1.1
    Host: example.com
    User-Agent: curl/7.60.0
    Accept: */*
    Content-Length: 416
    Content-Type: multipart/form-data; boundary=------------------------b5a1c465b6242b10
    Connection: close
    
    --------------------------b5a1c465b6242b10
    Content-Disposition: form-data; name="xxxxx"
    
    XXX-XX
    --------------------------b5a1c465b6242b10
    Content-Disposition: form-data; name="xxx_xxxx"
    
    XXXX00000000Xx0000000000000000000XX00.pdf
    --------------------------b5a1c465b6242b10
    Content-Disposition: form-data; name="xxx_xx"
    
    XXXX00000000Xx0000000000000000000XX00
    --------------------------b5a1c465b6242b10--