通过python发布问题

时间:2014-11-05 07:37:18

标签: python http post cgi

我有点麻烦。我试图发送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 个答案:

答案 0 :(得分:5)

看起来我需要将其字符串化为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 :(得分:1)

使用httplib替代POST:

* import 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()*

看看这是否有帮助。

答案 2 :(得分:0)

不确定这是否解决了问题,但如果我在网址的末尾添加斜杠,我会在执行代码时收到回复。

url =' https://hooks.slack.com/services/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/'