设置请求库内容长度

Set request library content length

我需要对服务器进行一些测试,所以我想对内容长度进行硬编码,而不希望请求库计算内容长度。

到目前为止我写的代码是这样的:

date = time.strftime("%a, %d %b %Y %H:%M:%S GMT",time.gmtime(time.time()))
sample_header = {
    "Host": "xyz.xyz.zyz.com",
    "Content-Type": "application/json; charset=utf-8",
    "Date": date        
    # "Authorization": "not_specified"
    }

sample_payload = {
   "ci":{
      "pev":1,
      "affid":"243324",
      "sdkv":"My SDK Version",
      "prn":"My Security Product",
      "pv":"1.0.1",
      "cliid":"4fe836859578e81ae5b0a061d6949634",
      "rid":234343
         },
    "q":[{"op":"url","url":"http://www.yahoo.com"}]
}

    def test_1677(self):
        self.tc_id="gtirest-1677"
        s = requests.Session()
        req = requests.Request('POST', url, headers=sample_header, data=json.dumps(sample_payload))
        prepared = req.prepare()
        # del prepared.headers['Content-Lenght']

        del prepared.headers['Content-Length']

        prepared.headers['Content-Lenght'] = 99999
        response = s.send(prepared)
        print "Response code"
        print response.status_code
        print response.text
        print response.request.headers

它给出了 400 Bad Request,但是当我发送相似的内容长度时,它给出了 413 entity too large 这是正确的,我如何在请求库中实现相同的结果。

我进行了 wireshark 捕获,它显示如下:

带请求库:

卷曲:

为什么在请求库中给出了 400 个错误请求。我可以看到负载现在在请求的情况下是正确的。

你拼错了header:

prepared.headers['Content-Lenght'] = 99999
#                             ^^

拼写为Lengtht,然后拼写为h

如果你设置的是header值,也不需要先删除header;如果您没有先删除 Content-Length header,您会注意到会有 两个 header 并且错字会跳转马上出去