2014-11-05 33 views
2

我遇到了一些麻烦。我正在尝试发送POST并尝试跟踪文档,但我似乎无法正确理解。通过python发布Post有问题

在GitHub上:https://github.com/trtmn/Python

引入请求的欢迎!

# Getting documentation from : 
#https://docs.python.org/2/howto/urllib2.html 
import urllib 
import urllib2 

url = 'https://hooks.slack.com/services/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' 
values = {"username": "webhookbot", "text": "This is posted to #general and comes from a bot named webhookbot.", "icon_emoji": ":ghost:"} 

data = urllib.urlencode(values) 
req = urllib2.Request(url, data) 
response = urllib2.urlopen(req) 
the_page = response.read() 

回答

3

看起来像我需要将其字符串化为JSON(我知道,但不知道如何)。感谢Tim G.的帮助。

因此,这里的功能代码:

import urllib2 
import json 

url = 'https://hooks.slack.com/services/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' 
values = {"username": "webhookbot", "text": "This is posted to #general and comes from a bot named webhookbot.", "icon_emoji": ":ghost:"} 

data = json.dumps(values) 
req = urllib2.Request(url, data) 
response = urllib2.urlopen(req) 
the_page = response.read() 
1

使用httplib的是后一种替代方案:

*进口httplib的

conn = httplib.HTTPSConnection(host) 
conn.request('POST',urI,request_body, headers)  
response = conn.getresponse() 
resp_status=response.status 
resp_reason=response.reason 
resp_body=response.read() 
conn.close()* 

看看这会有所帮助。