0

我试图POST使用包含完整冒号的标头发出请求,我将如何创建对象以使其正常工作?这是我的尝试:

    req = HTTPRequest(
          "http://myapp:8080/debug",
          method='POST', headers={'Accept': 'application/json',
                       "Accept-Language": "en_US",
                       'Authorization:Bearer': 'somelongstring'},
                       body= {'fancy':'dict'})

发布时,它会在请求标头中生成:

{'Accept': 'application/json',
 'Authorization\\': 'bearer: somelongstring',   # this is the line  
 'Content-Length': '276', 
 'Host': 'myapp:8080', 
 'Accept-Language': 'en_US', 
 'Accept-Encoding': 'gzip', 
 'Content-Type': 'application/x-www-form-urlencoded', 
 'Connection': 'close'}

当我尝试这个

    from urllib import parse
    auth_h = parse.quote('Authorization:Bearer')
    req = HTTPRequest(
          "http://myapp:8080/debug",
          method='POST', headers={'Accept': 'application/json',
                       "Accept-Language": "en_US",
                       auth_h: 'somelongstring'},
                       body= {'fancy':'dict'})

另一方面,这会产生:

{'Accept': 'application/json', 
 'Host': 'myapp:8080', 
 'Content-Length': '276', 
 'Authorization&#58Bearer': 'somelongstring',     # see this line
 'Accept-Language': 'en_US', 
 'Accept-Encoding': 'gzip',
 'Content-Type': 'application/x-www-form-urlencoded',
 'Connection': 'close'}

Authorization&#58bearer 不能也 'Authorization\\': 'bearer: somelongstring'不能工作,我需要它被接收 'Authorization:Bearer': 'somelongstring',所以我做错了什么?

4

1 回答 1

2

挑战在于您正在尝试添加无效的标头名称。您可能指的是 Authorize 标头,其值为Bearer:longstring. 所以你的第一个样本变成:

req = HTTPRequest(
          "http://myapp:8080/debug",
          method='POST', headers={'Accept': 'application/json',
                       "Accept-Language": "en_US",
                       'Authorization': 'Bearer:somelongstring'},
                       body= {'fancy':'dict'})
于 2013-11-14T18:03:34.350 回答