首页 > 解决方案 > 如何使用java在放心框架中传递大而复杂的xml正文

问题描述

我处理了少于 20 行的小型 xml 正文请求,并在 java 中为它创建了键值对。但我必须使用 acord xml 作为有效负载请求才能获得超过 250 行的响应。我尝试使用 form-data 提供 .xml 文件,但它不起作用。contentType 是 xml 格式,并且以 xml 格式接收响应。

如果在框架中编码,有人可以指导我正确的方向吗?

@Test
public void xmlPostRequest_Test() {

    RestAssured.baseURI = "http://localhost:8006";

    String requestBody = "<client>\r\n" +
        "    <clientNo>100</clientNo>\r\n" +
        "    <name>Tom Cruise</name>\r\n" +
        "    <ssn>124-542-5555</ssn>\r\n" +
        "</client>";

    Response response = null;

    response = given().
    contentType(ContentType.XML)
        .accept(ContentType.XML)
        .body(requestBody)
        .when()
        .post("/addClient");

    System.out.println("Post Response :" + response.asString());
    System.out.println("Status Code :" + response.getStatusCode());
    System.out.println("Does Reponse contains '100 Tom Cruise 124-542-5555'? :" + response.asString().contains("100 Tom Cruise 124-542-5555"));
}

标签: javaxml-parsingrest-assured

解决方案


您应该使用文件来传递 xml 有效负载。

请查看以下代码并提供反馈。它已经过测试和工作。

import static io.restassured.RestAssured.given;
import static io.restassured.RestAssured.when;
import static org.hamcrest.Matchers.is;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.filter.session.SessionFilter;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.Response;

public class XmlExample {
    //@Test
    public void postComplexXML() throws IOException {
        String FilePath="path\\to\\xml.xml";
        String XMLBodyToPost=generateStringFromResource(FilePath);
        RestAssured.baseURI="http://services.groupkt.com/state/get/IND/UP";
    Response res=   given().queryParam("key", "value").body(XMLBodyToPost).when().post().then().statusCode(201).and().
        contentType(ContentType.XML).extract().response();
    //Pass the RrstAssured Response to convert to XML
    XmlPath x=rawToXML(res);
    //Get country value from response
    String country=x.get("RestResponse.result.country");
    int size=x.get("result()");
    }

推荐阅读