记录学习经历
一个可用的实例如下。
关于lib几个函数的使用介绍参见这里: 这里
#!/usr/bin/python
#coding:utf-8
import httplib,urllib
httpClient =None
try:
params =urllib.urlencode({'uin':2852199330})
#headers = {"Content-Type": "application/json", "Accept": "text/plain"}
headers = {"Connection":"keep-alive","Accept":"text/xml","Content-Type":"application/json"}
httpClient=httplib.HTTPConnection('9.137.17.190',21091,30)
httpClient.request("POST",'/configs/set/shuozhuosh/cl_customer_tips_display_config',params,headers)
response =httpClient.getresponse()
print response.status
print response.reason
print response.read()
print response.getheaders()
except Exception ,e:
print e
finally:
if httpClient:
httpClient.close()
接受方收到的数据如下:
1、urllib中的urlencode函数
其作用是把key-value这样的键值对转换成“a=1&b=2”样式的字符串。比如:
import urllib
data={'a':'testaaa','name':'北冥大鱼鱼'}
urllib.urlencode(data)
'a=testaaa&name=%E5%8C%97%E5%86%A5%E5%A4%A7%E9%B1%BC%E9%B1%BC'
2、HTTPConnection.request()语法
语法:
HTTPConnection.request( method , url [ , body [ , headers ]] )
用法:调用request方法会向服务器发送一次请求
参数:
(1)method: 请求的方式,如’GET’,‘POST’,‘HEAD’,‘PUT’,'DELETE’等
(2)url: 请求的网页路径。如:’/index.html’
(3)body: 请求是否带数据。有些说说它要是字典,实际是胡扯的。
(4)headers: 请求是否带头信息。
注:关于body和headers部分参见官网。这里 由官网可知这里可以是字符串。
3、body发送json数据
前面说了body可以是字符串,所以生拼一个jsonf放进去就是可以的。
#!/usr/bin/python
#coding:utf-8
import httplib,urllib,json
httpClient =None
try:
headers = {"Content-type": "application/json", "Accept": "text/plain"}
httpClient=httplib.HTTPConnection('9.137.17.190',21091,30)
httpClient.request("POST",'/configs/set/cl_customer_tips_display_config?uin=2852199330',"{\"staffuin\":3007064412,\"value\":\"0\"}",headers)
# httpClient.request("POST",'/configs/set/cl_customer_tips_display_config?uin=2852199330',data,headers)
# httpClient.request("POST",'/configs/set/shuozhuosh/cl_customer_tips_display_config',params,headers)
response =httpClient.getresponse()
print response.status
print response.reason
print response.read()
print response.getheaders()
except Exception ,e:
print e
finally:
if httpClient:
httpClient.close()
收到的数据如下: