乐闻世界logo
搜索文章和话题

How to modify HTTP response body with Charles Proxy rewrite tool and regex?

1个答案

1

First, Charles Proxy is a widely used network debugging tool commonly employed in development and testing to monitor and modify HTTP and HTTPS requests and responses. To modify the HTTP response body using Charles Proxy and regular expressions, follow these steps:

1. Install and Configure Charles Proxy

First, ensure Charles Proxy is installed. After installation, launch Charles and configure your browser or device to route all network traffic through Charles. Typically, set the system or browser proxy settings to 127.0.0.1 (localhost) and Charles' port number (default is 8888).

2. Enable SSL Proxying Settings

Since most HTTP communications now use HTTPS, enable SSL proxying in Charles to view and modify HTTPS requests and responses. In the menu bar, select Proxy -> SSL Proxying Settings, and add the hosts to monitor.

3. Create Rewrite Rules

Next, navigate to Tools -> Rewrite, click the Add button at the bottom right to add a new rewrite rule. In the pop-up settings window, name the rule and specify its location (e.g., select Location and add specific URLs or URL patterns).

4. Set Rewrite Content

Within the created rule, click the Add button to add a rewrite item. You can choose to modify requests or responses; here, select to modify the response body. Then, in the Where section, select Body.

In the Match section, enter the pattern to match; regular expressions can be used here. For example, to change a field from 'false' to 'true' in the response, enter the regular expression ("someKey":\s*)false in the Match field.

Then, in the Replace section, enter the replacement content using backreferences from the regular expression to preserve parts; for example, input $1true, where $1 refers to the ("someKey":\s*) part in the Match section.

5. Enable Rewrite Rules

After configuration, ensure the checkbox for the rewrite rule is selected to activate it. Close the settings window and continue monitoring network traffic in the main window to verify the effect.

Example Suppose we monitor an API response with the following content:

json
{ "user": "guest", "access": false }

We want to create a rewrite rule to change "access": false to "access": true. We can set the regular expression to ("access":\s*)false and the replacement to $1true.

With these settings, you can observe and test the impact of modifying the response without changing server or client code, which is very useful during development and testing.

2024年7月20日 03:55 回复

你的答案