import urllib
#定义一个要提交的数据数组(字典)
data = {}
data['username'] = 'zgx030030'
data['password'] = '123456'
#定义post的地址
url = ' test.com/post/'
post_data = urllib.urlencode(data)
#提交,发送数据
req = urllib2.urlopen(url, post_data)
#获取提交后返回的信息
content = req.read()
一个http请求包括三个部分,分别为请求行,请求报头(请求头),消息主体(请求体),类似以下这样:
HTTP协议规定post提交的数据必须放在消息主体中,但是协议并没有规定必须使用什么编码方式。服务端通过是根据请求头中的Content-Type字段来获知请求中的消息主体是用何种方式进行编码,再对消息主体进行解析。具体的编码方式包括
1. 以form形式发送post请求
Reqeusts支持以form表单形式发送post请求,只需要将请求的参数构造成一个字典,然后传给requests.post()的data参数即可。
2. 以json形式发送post请求
可以将一json串传给requests.post()的data参数,
3. 以multipart形式发送post请求
Requests也支持以multipart形式发送post请求,只需将一文件传给requests.post()的files参数即可。
输出:
{“args”: {},
“data”: “”,
“files”: {
“file”: “Hello world!”
},
“form”: {},
“headers”: {……
“Content-Type”: “multipart/form-data boundary=467e443f4c3d403c8559e2ebd009bf4a”,
……
},
“json”: null,
……
}
---------------------
作者:weixin_40283480
来源:CSDN
原文:https://blog.csdn.net/weixin_40283480/article/details/79208413
版权声明:本文为博主原创文章,转载请附上博文链接!
#!/usr/bin/python#encoding=utf-8
'''
基于BaseHTTPServer的http server实现,包括get,post方法,get参数接收,post参数接收。
'''
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import io,shutil
import urllib
import os, sys
class MyRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
mpath,margs=urllib.splitquery(self.path) # ?分割
self.do_action(mpath, margs)
def do_POST(self):
mpath,margs=urllib.splitquery(self.path)
datas = self.rfile.read(int(self.headers['content-length']))
self.do_action(mpath, datas)
def do_action(self, path, args):
self.outputtxt(path + args )
def outputtxt(self, content):
#指定返回编码
enc = "UTF-8"
content = content.encode(enc)
f = io.BytesIO()
f.write(content)
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "text/htmlcharset=%s" % enc)
self.send_header("Content-Length", str(len(content)))
self.end_headers()
shutil.copyfileobj(f,self.wfile)