Request redirect not working for using static data

I am trying to use the redirect request example in my project but it is not working.
What I am doing:

  • I have a stored json for example <user.json>
  • I am planning to, pass this json when I capture user_url: /account/user
"""
This example shows two ways to redirect flows to other destinations.
"""
from libmproxy.models import HTTPResponse
from netlib.http import Headers

def request(context, flow):

    # Method 2: Redirect the request to a different server
    #if flow.request.pretty_host.endswith("/account/me/user"):
     #   flow.request.url = "file:///Users/xxx/Documents/workspace/xxxxxAutomation/ios/features/mock_data_test/user.json"

      mock_user = "file:///Users/xxx/Documents/workspace/xxxxxAutomation/ios/features/mock_data_test/user.json"

# Note: my real url is : https://www.abcd.net/account/me/user

      if flow.request.pretty_host.endswith("xxxx.net/account/me/user"):
             resp = HTTPResponse(
                 "HTTP/1.1", 200, b"OK",
                 Headers(Content_Type="application/json"),
                 str(mock_user)
             )
             flow.reply.send(resp)
Getting Error:
flow.reply.send(resp)\nAttributeError: Reply instance has no attribute 'send'

instead of mitmproxy.models I am using libmproxy.models because mitmproxy.models results into an error.

I tried everything under request pretty host and url but still it is not working.

Please let me know, how can I achieve it.

I got it working.Example:

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

import json

def request(context, flow):

      with open('/path_to_file/mock_data_test/user.json') as data_file:
          data = json.load(data_file)
          print(json.dumps(data, sort_keys=True, indent=4))
          new_data = json.dumps(data)

      if flow.request.pretty_url.endswith("/url/user"):
         resp = HTTPResponse(
                                 "HTTP/1.1",
                                 200,
                                 "OK",
                                 Headers(Content_Type="application/json"),
                                 str(new_data)
         )

         flow.reply(resp)
1 Like