multipart/form-data The other day, I implemented communication processing using Java's HttpURLConnection. Among them, I made a part that can be sent universally in the multipart / form-data format, but for some reason it is not recognized as a multipart / form-data request no matter how many times it communicates, and it takes a considerable amount of time to resolve it. I have spent it.
The cause is very ridiculous, is there anyone else who is addicted to this? It was like that, but I would like to write it as a memorandum.
By the way, when I wrote it first, it was the cause.
The general one is like this. The contents assembled in the following format are put on the Body and communicated.
multipart/form-body of data
--[Boundary string]
Content-Disposition: form-data; name="[Form name]"
<<Form contents>>
--[Boundary string]
Content-Disposition: form-data; name="[Form name]"; filename="[file name]"
Content-Type: text/plain
<<File contents>>
--[Boundary string]
・
・
・
Continues as much as you send
・
・
・
--[Boundary string]--
Write the Content-Type of the request header after multipart / form-data and the Boundary string after the Content-Type. The line feed code must be CRLF.
Looking at the request body of the sent request, there is no sign of misunderstanding compared to the above format, and there is no doubt that the Boundary specification of Content-Type in the request header is correct. Hmm?
If you communicate from Postman in form data format and compare it with the request that is recognized normally,
multipart/form-body of data
--[Boundary string]
There was no first "-". .. At first, I was not very familiar with the mechanism of multipart / form-data, so I made it by referring to the sites on the net, but on various sites, as a Boundary character string, "-------- random character string" Because it was a specification like this, I learned from it and specified the character string with "--------" at the beginning, and there was a lack of recognition that a separate "-" was required at the beginning. The cause was that it was difficult to confirm whether or not it was actually removed. (It's a story to read RFC properly.)
By the way, the last delimiter needs a "-" after it! (Reminder)
The belief is scary.
Write it down so that no one gets stuck with similar content. (Is there such a person?)
By the way, the following sites are recommended when testing HTTP communication. There are endpoints that return information about requests sent by GET or POST in the form of JSON, binary responses, and various other endpoints, so simple communication You can also test the communication fairly firmly from the confirmation of the contents.
If you don't know it, please use it. Make progress. httpBin: https://httpbin.org/
Recommended Posts