使用urllib发出发布请求 [英] Making post request using urllib
本文介绍了使用urllib发出发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试向API提供程序发出请求
I am trying to make request on API provider
curl "https://api.infermedica.com/dev/parse" \
-X "POST" \
-H "App_Id: 4c177c" -H "App_Key: 6852599182ba85d70066986ca2b3" \
-H "Content-Type: application/json" \
-d '{"text": "i feel smoach pain but no couoghing today"}'
此curl请求给出响应。
This curl request gives response.
但是当我尝试编写代码时,同样的请求
But same request when I try to make in code
self.headers = { "App_Id": "4c177c", "App_Key": "6852599182ba85d70066986ca2b3", "Content-Type": "application/json", "User-Agent": "M$
self.url = "https://api.infermedica.com/dev/parse"
data = { "text": text }
json_data = json.dumps(data)
req = urllib2.Request(self.url, json_data.replace(r"\n", "").replace(r"\r", ""), self.headers)
response = urllib2.urlopen(req).read()
它给出
Traceback (most recent call last):
File "symptoms_infermedia_api.py", line 68, in <module>
SymptomsInfermedia().getResponse(raw_input("Enter comment"))
File "symptoms_infermedia_api.py", line 39, in getResponse
response = urllib2.urlopen(req).read()
File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 410, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 448, in error
return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
推荐答案
这将是使用python的等效请求请求
库。
This would be the equivalent request using the python requests
library.
url = "https://api.infermedica.com/dev/parse"
headers = {
'App_Id': '4c177c',
'App_Key': '6852599182ba85d70066986ca2b3',
'Content-Type': 'application/json',
}
data = {'text': 'i feel stomach pain but no coughing today'}
r = requests.post(url, headers=headers, data=json.dumps(data))
print r.status_code
print r.json()
但是您真正的问题是您为其API使用了错误的标题键。它是 App_Id
和 App-key
,而不是 App_Id
和 App_key
。看起来像这样:
But your real problem is that you're using the wrong header keys for their api. It's App-Id
and App-key
, not App_Id
and App_key
. It would look like this:
headers = {
'App-Id': 'xx',
'App-key': 'xxxx',
'Accept': 'application/json',
'Content-Type': 'application/json',
'Dev-Mode': 'true'}
data = {'text': 'i feel stomach pain but no coughing today'}
r = requests.post(url, headers=headers, data=json.dumps(data))
同样值得注意的是,它们有一个 Python api 为您完成所有这些操作。
Also worth noting, they have a python api that does all this for you.
这篇关于使用urllib发出发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文