python 发起HTTP请求

  因为微信公众号群发需要调用高级群发接口,其中涉及到python发起HTTP请求,现在将相关实现操作记录如下:

  首先,HTTP请求分为GET和POST,如下所示:

  首先是发起get 请求:

# -*- coding: utf-8 -*-
import httplib
import urllib
try:
    
    httpClient =httplib.HTTPConnection('127.0.0.1',5000,timeout=30)
    httpClient.request('GET','/data/get/')
    response=httpClient.getresponse()
    print response.status
    print response.reason
    print response.read()
except Exception,e:
    print e
finally:
    if httpClient:
        httpClient.close()

  发起Http请求的时候,首先需要建立httpClient对象,建立的时候需要指定服务器的ip地址,端口号,以及超时时间。

  接下来正式发起HTTP 请求,需要指明获取数据的相对地址以及调用的方法,在这里,我们的方法为GET.

  最后,通过getresponse()方法可以获取服务器返回的信息。

  response.status 属性对应连接的状态

  response.reason 属性对应连接返回状态造成的原因

  response.read() 对应服务器返回的信息

接下来是发送post请求:

#-*- coding:utf8 -*-
#coding=utf-8
#author : zhouyang
import httplib,urllib
httpClient =None
try:
    params =urllib.urlencode({'name':'zhouyang','age':21})
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
    httpClient=httplib.HTTPConnection('127.0.0.1',5000,30)
    httpClient.request("POST",'/test/',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()

  发起POST请求的时候,基本的步骤是和GET类似的,只是需要设置请求头的内容,并且需要将需要传输的数据格式化之后再发送给服务器。数据格式化采用的是urlencode()方法,将dict转换为格式化之后的字符串。

  同时,在最后,我们输出了服务器回应的头内容,即:

  response.getheaders()

原文地址:https://www.cnblogs.com/zhoudayang/p/5261686.html