python3 httpConnection——post请求

#coding=utf-8

import http.client
import urllib.parse


#与服务器建立链接
url = 'code.ali.cn:80'

conn = http.client.HTTPConnection(url).  #python3

conn = httplib.HTTPConnection #python2


#向服务器发送请求
method="POST"
requrl = "http://code.ali.cn/v2/tickets-v2"
headerdata = {
  "Host": "code.ali.cn",
  "Accept-Encoding": "gzip",
  "User-Agent": "Android-Up366-Moblie 4.3.0",
  "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  "Connection": "Keep-Alive"
}
test_data = urllib.parse.urlencode({
  "username": "ali",
  "password": "fdd13a1557f78824820bf028db0e18d9",
  "ut": "c2dc7b2429847da1e4efcc97ef20d867a8161f2d2646680f53cedb93af07cb49",
})


conn.request(method=method,url=requrl,body=test_data,headers = headerdata)


#获取响应消息体
response = conn.getresponse()
print(response.status,response.reason)
data = response.read()
print(data)

#获取响应头部信息,列表形式
resheader=response.getheaders();
print(resheader)

#取出响应头部的Set-Cookie的值
responsehead = response.getheader('Set-Cookie')
print(responsehead)
conn.close()

#python2和python3加载模块

if re.match('^3.d.d', sys.version):
from http.client import HTTPConnection
import configparser
import urllib.parse as Urllib
elif re.match('^2.d.d', sys.version):
from httplib import HTTPConnection
import ConfigParser as configparser
import urllib as Urllib
原文地址:https://www.cnblogs.com/lgj8/p/12664600.html