我正在尝试向一个宁静的网络服务发送POST请求。我需要在请求中传递一些json
。它可以使用下面的curl命令
curl --basic -i --data '<json data string here>' -H Content-type:"text/plain" -X POST http://www.test.com/api
我需要一些帮助才能从Python发出上述请求。要从python发送此POST请求,到目前为止我有以下代码:
import urllib
url='http://www.test.com/api'
params = urllib.urlencode... #What should be here ?
data = urllib.urlopen(url, params).read()
我有以下三个问题:
请帮助 谢谢
答案 0 :(得分:2)
httplib
的文档有example发送帖子请求。
>>> import httplib, urllib
>>> params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
>>> headers = {"Content-type": "application/x-www-form-urlencoded",
... "Accept": "text/plain"}
>>> conn = httplib.HTTPConnection("bugs.python.org")
>>> conn.request("POST", "", params, headers)
>>> response = conn.getresponse()
>>> print response.status, response.reason
302 Found
>>> data = response.read()
>>> data
'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
>>> conn.close()
答案 1 :(得分:1)
答案 2 :(得分:1)
问题涉及将参数发送为“json”.. 你需要在标题中将Content-Type设置为application / json,然后在没有urlencoding的情况下发送参数。
例如:
url = "someUrl"
data = { "data":"ur data"}
header = {"Content-Type":"application/json","User-Agent":"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"}
#lets use httplib2
import httplib2
http = httplib2.Http()
response, send = http.request(url,"POST",headers=header,body=data)
答案 3 :(得分:1)
如果urllib.urlencode()
不是Content-Type
,则您不需要application/x-www-form-urlencoded
:
import json, urllib2
data = {"some": "json", "d": ["a", "ta"]}
req = urllib2.Request("http://www.test.com/api", data=json.dumps(data),
headers={"Content-Type": "application/json"})
print urllib2.urlopen(req).read()
答案 4 :(得分:0)
resources:
repositories:
- repository: e2e_fx
type: github
name: Azure/iot-sdks-e2e-fx
ref: refs/heads/master
endpoint: 'GitHub OAuth'
jobs:
- template: vsts/templates/jobs-gate-c.yaml@e2e_fx
答案 5 :(得分:-1)
这是json的POST请求的示例代码段。结果将打印在您的终端中。
import urllib, urllib2
url = 'http://www.test.com/api'
values = dict(data=json.dumps({"jsonkey2": "jsonvalue2", "jsonkey2": "jsonvalue2"}))
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
rsp = urllib2.urlopen(req)
content = rsp.read()
print content