关于send_post和send_get方法
来源:8-11 项目实战之结果回写

cloudonthesun
2021-07-03
老师,我在测试接口的时候这个接口是一个需要发送json参数的get请求,
然后在执行代码的时候就报错了。提示获取不到参数,
看了下后台报错信息,应该是传入的参数不符合格式所以没有获取到
org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public com.fanyu.mall.common.ApiRestResponse com.fanyu.mall.controller.ProductController.list(com.fanyu.mall.model.request.ProductListReq)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:161) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
fiddler抓包发现传参是按照webform传过去的,
我看res = requests.get(url,params=data,verify=False).text,我把params改成json后就能请求成功。
想问下老师,对于get/post请求,接口可能是json格式传参,也可能是url后面传参,也有可能是form-data等,对于这些不同的传参方式是要在send_post/send_get方法里增加一个形参,表示参数格式吗,然后在函数内部对这个参数判别,针对不同的格式设置不同的请求头的ContentType信息,然后再调用requests的get/post方法发送请求
打扰了老师,恳请老师能够指点
*********************************************************
def send_post(self,url,data):
print("进来了post请求||",type(data),"||",data)
if data:
res = requests.post(url,data=data,verify=False).text
else:
res = requests.post(url,verify=False).text
try:
res = json.loads(res)
except:
print("BaseRequest post res---------->decode error,res is still text")
return res
def send_get(self,url,data):
if data:
res = requests.get(url,params=data,verify=False).text
else:
res = requests.get(url,verify=False).text
try:
res = json.loads(res)
except:
print("BaseRequest get res---------->decode error,res is still text")
return res
***************************************************************************
1回答
-
1、如果是这样,你们前后端分离就做得不是很好。
2、如果针对这样 你的思考是对的,可以通过增加参数判断类型,然后去决定走什么。但是也可以直接requests.post(data=json.loads()) 这样去操作。当然 如果你接口校验不过,你可以把json.loads 转换为str(ps:这种其实是错误的,因为转换为str了。但是有时候接口规则教研 这个就需要你问你们后端开发看他怎么教研的了。)不过一般你直接contype 弄成json就ok。
032021-07-06