我正在寻找一种方法,为每个http请求添加2个自定义cookie。
browsermob代理(https://github.com/lightbody/browsermob-proxy)有removeHeaders()和addHeader()方法,但我该怎么做才能在请求中保留现有的cookie,但再添加2个cookie?
谢谢!
您可以使用此方法在每个请求/响应中调用自定义js代码https://github.com/lightbody/browsermob-proxy#http-请求操作Python 中的一些示例
def response_interceptor(self, js):
"""
Executes the javascript against each response
:param js: the javascript to execute
"""
r = requests.post(url='%s/proxy/%s/interceptor/response' % (self.host, self.port),
data=js,
headers={'content-type': 'x-www-form-urlencoded'})
return r.status_code
def request_interceptor(self, js):
"""
Executes the javascript against each request
:param js: the javascript to execute
"""
r = requests.post(url='%s/proxy/%s/interceptor/request' % (self.host, self.port),
data=js,
headers={'content-type': 'x-www-form-urlencoded'})
return r.status_code
和测试:
def test_request_interceptor_with_parsing_js(self):
"""
/proxy/:port/interceptor/request
"""
js = 'alert("foo")'
status_code = self.client.request_interceptor(js)
assert(status_code == 200)
正如我在上面回答的那样,您可以使用代理的REST API为通过代理发出的每个请求设置自定义js处理程序。
例如,您可以向每个请求添加任何自定义cookie:
curl-X POST-H"内容类型:text/plain"-d"js代码"http://10.100.100.20:8080/proxy/8081/interceptor/request
在php中,它看起来像:
/**
* @param Proxy $proxyObject
* @param array $cookiesArray
*/
protected function _setRequestCookies(Proxy $proxyObject, array $cookiesArray)
{
foreach ($cookiesArray as $nameString => $valueString) {
$cookiesArray[$nameString] = $nameString . '=' . $valueString;
}
$jsHandlerString = sprintf(
'var c = request.getMethod().getFirstHeader("Cookie") ? request.getMethod().getFirstHeader("Cookie").getValue() : ""; request.getMethod().setHeader("Cookie", c + "; %s");',
implode('; ', $cookiesArray)
);
$urlString = sprintf('%sproxy/%u/interceptor/request', $this->_hubUrlString, $proxyObject->getPort());
$this->_requesterObject->makeRequest($urlString, Requester::REQUEST_METHOD_POST, $jsHandlerString);
}