socket手动发送http包头
说明
GET的头部
"""GET %s HTTP/1.0\r\nHost: %s\r\n\r\n""" % ("/test.html?a=1&b=2","127.0.0.1:8000")
POST的头部及data
需要指定Content-Length和Content-Type
"""POST %s HTTP/1.1\r\nHost: %s\r\nContent-Length: 19\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\na=1&b=2&c=3&d=4&e=5""" % ("/test.html","127.0.0.1:8000")
示例
def test(req): if req.method == "GET": print(req.GET) print(req.body) return render(req,"test.html") elif req.method == "POST": print(req.POST) print(req.body) return HttpResponse("...") else: print(req.POST) print(req.body) return HttpResponse("...")
# -*- coding:utf-8 -*- import socket client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client.connect(("127.0.0.1",8000)) # GET text = """GET %s HTTP/1.0\r\nHost: %s\r\n\r\n""" % ("/test.html?a=1&b=2","127.0.0.1:8000") client.send(bytes(text,encoding="utf-8")) res = client.recv(8192) print(res) # b'HTTP/1.1 200 OK\r\nDate: Tue, 15 May 2018 11:44:26 GMT\r\nServer: WSGIServer/0.2 CPython/3.6.3\r\nContent-Type: text/html; charset=utf-8\r\nX-Frame-Options: SAMEORIGIN\r\nContent-Length: 356\r\n\r\n<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="UTF-8">\n <title>Title</title>\n</head>\n<body>\n <h1>test\xe9\xa1\xb5\xe9\x9d\xa2</h1>\n <form action="" method="POST" novalidate>\n\n <input type="text" name="name">\n <input type="text" name="age">\n <input type="email" name="email">\n <input type="submit">\n </form>\n</body>\n</html>' ''' server端: <QueryDict: {'a': ['1'], 'b': ['2']}> # request.GET b'' # request.body ''' ############################################################### # POST import socket client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client.connect(("127.0.0.1",8000)) text = """POST %s HTTP/1.1\r\nHost: %s\r\nContent-Length: 19\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\na=1&b=2&c=3&d=4&e=5""" % ("/test.html","127.0.0.1:8000") # text = """POST %s HTTP/1.1\r\nHost: %s\r\nContent-Length: 19\r\nContent-Type: application/json\r\n\r\na=1&b=2&c=3&d=4&e=5""" % ("/test.html","127.0.0.1:8000") # Content-Length:data的长度,19字节对应‘a=1&b=2&c=3&d=4&e=5’ # Content-Type: application/x-www-form-urlencoded 对应form格式的数据 # Content-Type: application/json # 如果是json,则数据只在request.body里,浏览器的Request Payload字段 client.send(bytes(text,encoding="utf-8")) res = client.recv(8192) print(res) # b'HTTP/1.1 200 OK\r\nDate: Tue, 15 May 2018 11:43:25 GMT\r\nServer: WSGIServer/0.2 CPython/3.6.3\r\nContent-Type: text/html; charset=utf-8\r\nX-Frame-Options: SAMEORIGIN\r\nContent-Length: 3\r\n\r\n...' ''' server端: Content-Type: application/x-www-form-urlencoded 结果如下: <QueryDict: {'a': ['1'], 'b': ['2'], 'c': ['3'], 'd': ['4'], 'e': ['5']}> # request.POST b'a=1&b=2&c=3&d=4&e=5' # request.body Content-Type: application/json结果如下: <QueryDict: {}> # request.POST b'a=1&b=2&c=3&d=4&e=5' # request.body '''

浙公网安备 33010602011771号