[英]How to send form-data in api using Rest-assured
您需要设置所需的内容类型,即“multipart/form-data”并将多部分请求规范添加到请求中。 例如。
given()
.contentType("multipart/form-data")
.multiPart("file", "filename")
.multiPart("key", "value")
.when()
.put(endpoint);
如果您正在上传文件,请务必包含一个文件对象。 它应该如下所示:
given()
.contentType("multipart/form-data")
.multiPart("id", "123")
.multiPart("file", new File("./src/test/resources/test-file.txt"))
.post("api/endpoint")
.then()
...
大多数时候我们需要将图像转换为 readFileToByteArray。
String file = "/Users/Downloads/file.png";
byte[] fileContent = FileUtils.readFileToByteArray(new File(file));
RestAssured.baseURI = "Enter Base uri";
Response res = given()
.header("Accept", "application/json")
.header("Content-type", "multipart/form-data")
.formParam("token", "08bc73deff88dd3d44bb1bf65b55d4ff")
.multiPart("asset", "image/png", fileContent).when()
.post("api/endpoint");
System.out.println(res.getStatusCode());
System.out.println(res.jsonPath().prettify());
请确保图像 mime 类型(在示例中指定为“image/png”)。
String body = given().
header("Origin", "http://3........80").header("Upgrade-Insecure-Requests", "1").
header("Referer", "http://........80/").header("Accept-Encoding", "gzip, deflate").
header("Accept-Language", "en-US,en;q=0.9").
formParam("message", getFormParamsMap()).
when().post("http://.....0/process-message").then().statusCode(200).extract().asString();
static Map<String, String> getFormParamsMap() {
Map<String, String> formParams = new HashMap<>();
formParams.put("g...me", "us-ma-boston");
formParams.put("s..score_cold..u", "31");
return formParams;
}
// uploading image on click of upload button
//fileNames is state
const [fileNames,SetfileNames] = useState("");
const updatecsvfile = (e) => {
e.preventDefault();
const formdata = new FormData();
formdata.append("document", fileNames);
let verify = localStorage.getItem("_id");
console.log(verify);
console.log("Data", formdata);
// posting to api by formdata
axios
.post(`${SERVER_URL}/uploadDocument?_id=${docids}`, formdata)
.then((res) => {
console.log("res", res.data.status);
let Status = res.data.status;
if (Status === "success") {
window.$("#uploadproject_doc").modal("hide");
window.$("#doc_added").modal("show");
window.setTimeout(function () {
window.location.reload();
}, 2000);
} else {
alert("Details are already Exists");
}
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.