版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/haishu_zheng/article/details/82380934
一、Get请求
如果你要做一个App项目,比如iOS或安卓项目,这时App和后端的项目是分离的。
此时要发网络请求,可以采用Get方式,也可以采用Post方式。
这里先介绍Get方式。
新建client_get.py,模拟客户端的GET请求
client_get.py中的完整代码为
import urllib.request
url = 'http://127.0.0.1:8000/mainpage?param1=hello¶m2=world'
req = urllib.request.Request(url)
data = urllib.request.urlopen(req).read()
print(data)
服务器端FirstWebDemo中的views.py作少量改动,其他地方不用动。
修改后的views.py中的完整代码为:
from django.shortcuts import render
# Create your views here.
def index(request):
print(request.GET.get("param1"))
print(request.GET.get("param2"))
return render(request, 'index.html')
注意,PyCharm中修改代码后,不用重启PyCharm,只要保存代码后,PyCharm会自动部署新代码,很方便
在CMD窗口运行客户端代码,运行结果如下
服务器端收到客户端的GET请求后,运行结果如下
二、Post请求
除了发送GET请求外,还可以发送POST请求。
新建client_post.py,模拟客户端的POST请求
client_post.py中的完整代码为
import requests
import json
url = 'http://127.0.0.1:8000/mainpage' #django接口路径
parms = {
'name' : 'This is request from client', #发送给服务器的内容
}
headers = { #请求头信息
'User-agent' : 'none/ofyourbusiness',
'Spam' : 'Eggs'
}
resp = requests.post(url, data=parms, headers=headers) #POST请求
print(resp)
#服务器返回的数据
text = resp.text
print(text)
服务器端FirstWebDemo中,只需要修改view.py中的代码:
from django.shortcuts import render
from django.http import JsonResponse
# Create your views here.
def index(request):
data={'name':'This is response data from server.'} #返回给客户端的数据
print(request.body)
if request.method=="POST":
print(request.POST) #查看客户端发来的请求内容
return JsonResponse(data) #通过django内置的Json格式,返回给客户端数据
在CMD窗口运行client_post.py后,得到403错误,表示服务器拒绝或禁止访问。
服务器端提示的错误则是:
Forbidden (CSRF cookie not set.): /mainpage
[24/Aug/2018 19:39:06] "POST /mainpage HTTP/1.1" 403 2868
将服务器端settings.py中的 ‘django.middleware.csrf.CsrfViewMiddleware’, 注释起来
再次在CMD窗口中运行客户端代码client_post.py,运行结果为
服务端的运行结果为
从上面的结果可以看出,客户端和服务器端可以正常通信。
想了解小朋友学编程可加QQ 307591841 或微信 307591841
关注微信公众号请扫二维码