python 发送请求到接口实现数据和文件的传输

1.引入requests模块

import requests

2.设置请求头

headers2 = {'Content-Type': 'application/json'}

3.设置请求参数

3.1 如果只是传输普通的json数据

# 需要传输的参数
data = {"lesson": "Operation System", "score": 100}
r = requests.post('http://localhost:3010/v1/carstatistic-3003/carInfo/countCarInfo', headers=headers2,json=data,
                  verify=False)
r.headers
print(r.text)

整体代码:

  • python
      import requests
    
      headers2 = {'Content-Type': 'application/json'}
      data = {"name": "ninesun", "age": 21}
      r = requests.post('http://localhost:3010/v1/carstatistic-3003/carInfo/countCarInfo', headers=headers2,json=data,
                      verify=False)
      r.headers
      print(r.text)
    
  • 后端
      @RequestMapping(value = "carInfo/countCarInfo", method = RequestMethod.POST)
          public String countCarInfo(@RequestBody Map<String, Object> map) {
              String name=map.get("name").toString();
              String age=map.get("age").toString();
              return "测试";
          }
    

3.2如果传输的数据中包含文件数据

3.2.1 仅仅传输文件

  • python
    def post_file(url, file_path):
        with open(file_path, 'rb') as f:
            result = requests.post(url, files={'file': f})
        return result
    r=post_file("http://localhost:3010/v1/carstatistic-3003/carInfo/saveCarInfoFile",
            "C:\\Users\\NineSun\\Desktop\\cs\\1.jpg")
    r.headers
    print(r.text)
    
  • 后端
      @RequestMapping(value = "/carInfo/saveCarInfoFile", method = RequestMethod.POST)
          public String saveCarInfoFile(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
              String fileName=null;
              try {
                  fileName=file.getOriginalFilename();
              } catch (Exception e) {
                  
                  e.printStackTrace();
              }
              return("获取文件成功");
          }
    

此处有个对应关系:
在这里插入图片描述

3.2.2 传输文件和数据

data = {"k1" : "v1"}
files = {
  "field1" : open("1.png", "rb")
}
r = requests.post("http://httpbin.org/post", data, files=files)
  • 1
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZNineSun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值