python http请求和响应如何工作

时间:2010-04-12 06:28:39

标签: python http

我是python的新手,我有任务所以我需要扫描wifi并将数据发送到服务器,下面是我必须发送的格式,这在手动输入浏览器URL文本时工作正常盒子,

http://223.56.124.58:8080/ppod-web/ProcessRawData?data={"userId":"2220081127-14","timestamp":"2010-04-12 10:54:24","wifi":{"ssid":"guest","rssi":"80"}}

这是我的代码:

import httplib  
import urllib

params = urllib.urlencode('{\"userId\":\"20081127-14\",\"timestamp\":\"2010-04-12 10:54:24\",\"wifi\":{\"ssid\":\"guest\",\"rssi\":\"80\"}}')

headers = {"Content-type":"application/x-www-form-urlencoded","Accept":"text/plain"}
conn = httplib.HTTPConnection("http://223.56.124.58:8080")
conn.request("POST","ppod-web/ProcessRawData?data=",params,headers)
response = conn.getresponse()   
print response.status  
print "-----"  
print response.reason  
data = response.read()   
print data
conn.close()

感谢

3 个答案:

答案 0 :(得分:10)

最有可能的问题是与您在问题中发布的脚本的问题是您无法直接执行的操作:

conn=httplib.HTTPConnection("http://223.56.124.58:8080/wireless") 

getaddrinfo()中触发异常,该异常调用返回EAI_NONAME的C函数getaddrinfo()

  

节点或服务未知;或者节点和服务都是NULL;或者在hints.ai_flags中指定了AI_NUMERICSERV,而service不是数字端口号字符串。“

传递给getaddrinfo的参数显然存在问题,您很可能正在尝试获取"223.56.124.58:8080/wireless"主机的信息。哎呀!

实际上,您无法直接连接到URL地址。 As the documentation clearly states and shows,您连接到服务器

conn = httplib.HTTPConnection("223.56.124.58", 8080)

然后你可以这样做:

conn.request("POST", "wireless", params, headers)

使用实际

conn.request("POST","http://202.45.139.58:8080/ppod-web",params,headers)

即使连接正确形成,也可以将帖子发送到http://202.45.139.58:8080/http://202.45.139.58:8080/ppod-web。你真正想要的是:

conn = httplib.HTTPConnection("202.45.139.58", 8080)
conn.request("POST", "ppod-web", params, headers)

此行显示错误,因为很可能HTTPConnection是一个惰性对象,只在您调用request()时尝试实际连接到服务器。


完成上述操作后,您需要修复params

>>> urllib.urlencode({"wifi":{"ssid":"guest","rssi","80"}})
SyntaxError: invalid syntax
>>> urllib.urlencode({"wifi":{"ssid":"guest","rssi":"80"}})
'wifi=%7B%27rssi%27%3A+%2780%27%2C+%27ssid%27%3A+%27guest%27%7D'

为了得到你认为想要得到的东西,你应该这样做:

>>> urllib.urlencode({"data": {"wifi":{"ssid":"guest","rssi":"80"}}})
'data=%7B%27wifi%27%3A+%7B%27rssi%27%3A+%2780%27%2C+%27ssid%27%3A+%27guest%27%7D%7D'

答案 1 :(得分:1)

而不是:

conn = httplib.HTTPConnection("http://223.56.124.58:8080/wireless")
conn.request("POST", "data", params, headers)  

尝试:

conn = httplib.HTTPConnection("223.56.124.58", port=8080)
conn.request("POST", "/wireless", params, headers)

不确定它是否能解决您的所有问题,但至少您的代码将符合方法/构造函数签名。

答案 2 :(得分:0)

回溯并非来自您粘贴的相同代码。

在错误回溯上有一行:

conn.request("POST","http://202.45.139.58:8080/ppod-web",params,headers)

它是http.py的第9行,但它不在你粘贴的代码上。

请粘贴实际代码。