This is a revised backport of 5776d97da3 and the following fixup https://github.com/gabrielfalcao/HTTPretty/pull/341
5776d97da3