设置请求库内容长度

时间:2015-02-06 14:22:18

标签: python python-2.7 curl python-requests

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

我写的代码到现在为止如下:

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个错误请求,但是当我发送类似的内容长度时,它给出413实体太大,这是正确的,我如何在请求库中实现相同。

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

使用请求库: Wireshark Capture request

卷曲:

Wireshark Capture curl

为什么在请求库中它会给出400个错误请求。我可以看到有效载荷现在是正确的,请求。

1 个答案:

答案 0 :(得分:1)

你拼错了标题:

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

拼写为Lengtht然后h

如果您要设置标头值,则无需先删除标头;如果你没有先删除Content-Length标题,你会注意到有两个标题,并且输入错误会立即跳出来。