python发起http请求(httplib)

记录学习经历

一个可用的实例如下。

关于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()

收到的数据如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

焱齿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值