Under the hood: An HTTP request with multipart/form-data

2 comments    Posted on February 6th, 2011

Check yourself, do you know what an HTTP request looks like coming over the wire? No, not the raw bits or the flowing electrons. Just try to picture the actual HTTP request body as text. Now imagine what it looks like if the HTTP request has an image attached. Here it is. This is what the internet is built on.

/
User-Agent: curl/7.21.2 (x86_64-apple-darwin)
Host: localhost:8080
Accept: */*
Content-Length: 1143
Expect: 100-continue
Content-Type: multipart/form-data; boundary=----------------------------83ff53821b7c

------------------------------83ff53821b7c
Content-Disposition: form-data; name="img"; filename="a.png"
Content-Type: application/octet-stream

?PNG

IHD?wS??iCCPICC Profilex?T?kA?6n??Zk?x?"IY?hE?6?bk
Y?<ߡ)??????9Nyx?+=?Y"|@5-?M?S?%?@?H8??qR>?׋??inf???O?????b??N?????~N??>?!?
??V?J?p?8?da?sZHO?Ln?}&???wVQ?y?g????E??0
 ??
   IDAc????????-IEND?B`?
------------------------------83ff53821b7c
Content-Disposition: form-data; name="foo"

bar
------------------------------83ff53821b7c--

You don’t always need to know what’s under the hood. But sometimes, it’s just magical to realize that the thing you’re using everyday is nothing more than this. What other protocols do you take for granted yet find completely amazing?

To watch raw HTTP requests yourself

  1. Get reflect.py — an echo server for HTTP requests
  2. Run this in terminal #1 python reflect.py
  3. Run this in terminal #2 curl -X POST -F foo=bar -F img=@a.png localhost:8080

2 responses so far

  1. Eric Larson says:

    I used to ask this as an interview question, not so much for accuracy or anything, but simply to see if the person realized what was actually happening when they used that library to pull some JSON or HTML.

  2. Luke says:

    Yep, works great. Now, if I were on the receiving end, would you have an idea how to extract the body parts into something usable? Just curious.

Leave a reply