[英]Sending a POST request using httplib
I'm trying to send data using httplib
. 我正在尝试使用httplib
发送数据。 Here is my code: 这是我的代码:
headers = {'User-agent': 'agent','Accept': 'application/json'}
params = { 'api_key':'kjdksnjd45555','ts':455555555}
data = {'job1':42,'job2':85}
params['data'] = json.dumps(data,separators =(',',':'))
re = requests.post(url,headers,params)
print re.json()
When I using requests, it work very nice, but not when I use httplib
当我使用请求时,它工作得很好,但是当我使用httplib
时却不能
params = urllib.urlencode(params)
con = httplib.HTTPConnection('api.sandbox.gengo.com')
con.request("POST", "/api/v", param, headers)
r2 = con.getresponse()
r2.read()
It returns the following error : 它返回以下错误:
"msg":"\\"api_key\\" is a required field"}
(This means that it can not recover my data.) (这意味着它无法恢复我的数据。)
What can I try? 我可以尝试什么? Thanks. 谢谢。
Looks like you have a typo on line: 看起来您有错字:
con.request("POST", "/api/v", param, headers)
Shouldn't that be params
and not param
. 那不应该是params
而不是param
。 This would explain why the server is responding about the missing api_key
这可以解释为什么服务器响应缺少的api_key
The third argument of HTTPConnection.request is not the http request parameters. HTTPConnection.request的第三个参数不是http请求参数。 It is the POST request body. 它是POST请求正文。 The parameters are part of the url and should be sent as such. 参数是url的一部分,应按原样发送。
https://docs.python.org/3/library/http.client.html?#http.client.HTTPConnection https://docs.python.org/3/library/http.client.html?#http.client.HTTPConnection
Your code has two mistakes. 您的代码有两个错误。 First you are using param
instead of params
in your third line, but also you are passing the parameters as request body not as request parameters. 首先,在第三行中使用的是param
而不是params
,但是您将参数作为请求正文而不是作为请求参数传递。
Try next code: 尝试下一个代码:
params = urllib.urlencode(params)
con = httplib.HTTPConnection('api.sandbox.gengo.com')
con.request("POST", "/api/v?" + params, "", headers)
r2 = con.getresponse()
r2.read()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.