使用python向lewei POST数据

参考网上代码做了必要修改

 

 1 # encoding: utf-8
 2 
 3 import socket, serial, time
 4 
 5 HOST = "open.lewei50.com"
 6 PORT = 80
 7 user_key = '2c2a9948d4c049c18560ddbfb46930d8'
 8 
 9 post_sch = \
10     "POST /api/v1/gateway/UpdateSensors/01 HTTP/1.1 \r\n" + \
11     "Host: open.lewei50.com \r\n" + \
12     "Content-Length: {msg_len} \r\n" + \
13     "userkey: %s " % user_key + \
14     "\r\n\r\n" + \
15     "{msg}\r\n"
16 
17 
18 def send_data(msg):
19 
20     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
21     s.settimeout(None)
22     s.connect((HOST, PORT))
23 
24     post_data = post_sch.format(msg_len=len(msg), msg=msg)
25     print post_data
26 
27     print '==== sent already ==== '
28     s.send(post_data)
29 
30     time.sleep(2)
31 
32     #re = s.recv(20000, socket.MSG_DONTWAIT)
33     re = s.recv(20000)
34     
35     print '==== message received ===='
36     print re
37 
38     s.close()
39 
40 

41 send_data('[{"Name":"t9","Value":"20"}]') 

 

 结果

 1 POST /api/v1/gateway/UpdateSensors/01 HTTP/1.1 
 2 Host: open.lewei50.com 
 3 Content-Length: 28 
 4 userkey: 2c2a9948d4c049c18560ddbfb46930d8 
 5 
 6 [{"Name":"t9","Value":"20"}]
 7 
 8 ==== sent already ==== 
 9 ==== message received ====
10 HTTP/1.1 200 OK
11 Date: Sun, 15 Mar 2015 15:38:26 GMT
12 Content-Type: application/json; charset=utf-8
13 Content-Length: 44
14 Connection: keep-alive
15 Cache-Control: private
16 Set-Cookie: SERVERID=a4a5b2bbca16d8c8b2ba6d5b6e55f36e|1426433905|1426433905;Path=/
17 

18 {"Successful":true,"Message":"Successful. "} 

posted on 2015-03-15 23:44  ardypro  阅读(690)  评论(1)    收藏  举报