如何使用 java 放心上传文件

How to upload a file in restassured with java

我们有一个 API,它从系统中获取一个文件并显示在应用程序上,为此我正在尝试放心地实现自动化 Java

我试过了,把图片改成二进制代码,然后把它作为参数添加进去,但是不行。

Map<String, String> paramSample = new HashMap<>();
    paramSample.put("api_key", "A813302*************");
    paramSample.put("method", "my");
    paramSample.put("body", "{\n" +
            "  \"to\":\"91xxxxxxxx\",\n" +
            " \"type\": \"image\", \"image\" : {\"caption\" : \"{{caption}}\"},\n" +
            "\"callback\":\"{{callback}}\"\n" +
            "}");
    paramSample.put("from", "91xxxxxxx");
    paramSample.put("file","C:\Users\sobhit.s\Pictures\SMS-2047.png");
    RequestSpecification request = given();
    Response responseSample = request.params(paramSample).get(ExecutionConfig.BASE_URL).then().extract().response();
    String res=responseSample.prettyPrint();

响应是-

{
    "status": "xxxx",
    "message": "Invalid file format. Upload valid file."
}

首先,如果您不确定,请在 Postman 中执行此操作,然后在代码中重新创建相同的内容。 这样你就会有一个 post 人来演示你的编码问题。

仅对参数使用 .queryParam(),不对正文内容使用。正文内容应在 .body()

使用.multiPart()将文件作为多部分任务上传。希望这可以帮助。

given().queryParam(
            "api_key", "A813302*************", 
            "method", "my",
            "from", "91xxxxxxx")
            .body("{\n" +
            "  \"to\":\"91xxxxxxxx\",\n" +
            " \"type\": \"image\", \"image\" : {\"caption\" : \"{{caption}}\"},\n" +
            "\"callback\":\"{{callback}}\"\n" +
            "}")
            .multiPart(new File("C:/Users/sobhit.s/Pictures/SMS-2047.png"))
            .when()
            .get(ExecutionConfig.BASE_URL)
            .prettyPrint();