Return custom response with mitmproxy

Wärting picture Wärting · Jan 8, 2016 · Viewed 8.3k times · Source

I'm trying to return custom response when using mitmproxy with the following code

from libmproxy.models import HTTPResponse
from netlib.http import Headers

def request(context, flow):
    if flow.request.pretty_url.endswith("example.com/index.php"):
        resp = HTTPResponse(
            [1, 1], 200, "OK",
            Headers(Content_Type="text/html"),
            "<html><body>hello world</body></html>")
        flow.reply(resp)

But the result is not as expected, in browser it shows up with http status codes, headers och body as clear text

[1,1] 200 OK
Content-Type: text/html

<html><body>hello world</body></html>

how can i return it as actual "http" response so that chrome render it as html?

Answer

xliiv picture xliiv · Jun 8, 2019

The snippet should looks like this

from mitmproxy import http


def request(flow):
    if flow.request.pretty_url.endswith("example.com/index.php"):
        flow.response = http.HTTPResponse.make(
            200,
            "<html><body>hello world</body></html>",
            {"content-type":"text/html"},
        )

for the newer versions of mitmproxy.