在服务端自动化测试过程中,文件上传类型的接口对应的请求头中的 content-type 为 multipart/form-data; boundary=…,碰到这种类型的接口,使用 Java 的 REST Assured 或者 Python 的 Requests 均可解决。
实战练习
Python 版本
在 Python 版本中,可以使用 files 参数上传文件,files 要求传递的参数内容为字典格式,key 值为上传的文件名,value 通常要求传递一个二进制模式的文件流。
>>> url = 'https://httpbin.ceshiren.com/post' >>> files = {"hogwarts_file": open("hogwarts.txt", "rb")} >>> r = requests.post(url, files=files) >>> r.text { "args": {}, "data": "", "files": { "hogwarts_file": "123" }, "form": {}, ...省略... "url": "https://httpbin.ceshiren.com/post" }
Java 版本
Java 需要使用 given() 方法提供的 multiPart() 方法,第一个参数为 name, 第二个参数需要传递一个 File 实例对象,File 实例化过程中,需要传入上传的文件的绝对路径+文件名。
import java.io.File; import static io.restassured.RestAssured.*; public class Requests { public static void main(String[] args) { given().multiPart("hogwartsFile", new File("绝对路径+文件名")). when().post("https://httpbin.ceshiren.com/post").then().log().all(); } }
响应内容为
{ "args": { }, "data": "", "files": { "hogwarts_file": "123" }, "form": { }, "headers": { ...省略... }, "json": null, "origin": "119.123.207.174", "url": "https://httpbin.ceshiren.com/post" }
image1080×224 26.5 KB使用抓包工具抓取过程数据数据,可以清楚看到传递数据过程中,如果是 Java 版本,name 传递内容为 multiPart() 方法的第一个参数,在 Python 版本中为 files 参数传递的字典的 key 值,而 filename 不论是 Java 版本还是 Python 版本,传递的内容均为传递文件的文件名。
原文地址:https://www.jb51.cc/wenti/3283782.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。