使用urllib发布帖子请求

时间:2017-01-29 04:44:29

标签: python curl request urllib2

我正在尝试向API提供商发出请求

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"}'    

此卷曲请求给出了响应。

但是当我尝试在代码中进行相同的请求时

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

2 个答案:

答案 0 :(得分:2)

这将是使用python requests库的等效请求。

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-IdApp-key,而不是App_IdApp_key。它看起来像这样:

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可以为你做这一切。

答案 1 :(得分:1)

json_data = json.dumps(data)不是准备POST数据的正确方法。

您应该使用urllib.urlencode()来完成这项工作:

import urllib
data = { "text": text }
req = urllib2.Request(self.url, urllib.urlencode(data), self.headers)
response = urllib2.urlopen(req).read()

Docs

  

class urllib2.Request(url [,data] [,headers] [,origin_req_host] [,   unverifiable])这个类是URL请求的抽象。

     

数据可以是指定要发送到服务器的其他数据的字符串,   如果不需要此类数据,则为“无”。目前HTTP请求是   只有使用数据的人; HTTP请求将是POST而不是   提供数据参数时获取。数据应该是缓冲区   标准application / x-www-form-urlencoded格式。的的   urllib.urlencode()函数采用2元组的映射或序列   并以此格式返回一个字符串。