首页 > 解决方案 > 使用带有 REST 方法的 java 代码发送 XML 请求并从 API 读取 XML 响应(Insomnia / SoapUI)

问题描述

目标概述:(1)将 XML 文件保存到 IntelliJ 中的字符串元素(2)将请求 XML 发送到 http 端点(3)从 http 端点获取响应 XML

到目前为止,我已经能够读取 XML 响应,但在尝试发送请求时不断收到错误。我有没有实现 REST 方法的工作方法,但更愿意在我的项目中使用这些方法。这是一种基本的方法,因为我仍在学习,因此非常感谢任何提示。想更接近

到目前为止,我的尝试是将 xml 请求设置为要发送到端点的字符串,然后从同一端点读取响应。下面是我尝试过的尚未严重依赖 REST 方法的代码。每当我尝试发送请求时,都会收到一个错误,即不允许使用此方法。是否有关于我可以编辑以使此请求正常工作的当前代码的建议?

package com.tests.restassured;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;


public class VIVPXMLResponseTest {

    public static void main(String[] args) {
        VIVPXMLResponseTest vivpXMLResponseTest = new VIVPXMLResponseTest();
        vivpXMLResponseTest.getXMLResponse("Success");
    }

    public void getXMLResponse(String responseCode) {
        String wsURL = "http://localhost:8080/hello/Hello2You";
        URL url = null;
        URLConnection connection = null;
        HttpURLConnection httpConn = null;
        String responseString = null;
        String outputString = "";
        ByteArrayOutputStream bout = null;
        OutputStream out = null;
        InputStreamReader isr = null;
        BufferedReader in = null;

        String xmlInputRequest = "<pasteXMLrequestHere>";

        try {
            url = new URL(wsURL);                           // create url object using our webservice url
            connection = url.openConnection();               // create a connection
            httpConn = (HttpURLConnection) connection;          // cast it to an http connection

            byte[] buffer = new byte[xmlInputRequest.length()];    // xml input converted into a byte array
            buffer = xmlInputRequest.getBytes();                   // put all bytes into buffer

            String SOAPAction = "";
            //Set the appropriate HTTP parameters
            httpConn.setRequestProperty("Content-Length", String
                    .valueOf(buffer.length));
            httpConn.setRequestProperty("Content-Type",
                    "text/xml; charset=utf-8");

            httpConn.setRequestProperty("SOAPAction", SOAPAction);
            httpConn.setRequestMethod("POST");
            //httpConn.setRequestMethod("GET");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            out = httpConn.getOutputStream();
            out.write(buffer);                              // write buffer to output stream
            out.close();

            //Read response from the server and write it to standard out
            isr = new InputStreamReader(httpConn.getInputStream()); //use same http connection, call getInputStream
            in = new BufferedReader(isr);
            while ((responseString = in.readLine()) != null)        //read each line
            {
                outputString = outputString + responseString;       //put into string -- may need to change if long file
            }
            System.out.println(outputString); //print out the string
            System.out.println(" ");

            //Get response from the web service call
            Document document = parseXmlFile(outputString);         //parse the XML - gets back raw XML - returns as document object model
            NodeList nodeLst = document.getElementsByTagName("ns:Code"); //where success / failure response is written
            NodeList nodeLst2 = document.getElementsByTagName("ns:Reason"); //where success / failure response is written
            String webServiceResponse = nodeLst.item(0).getTextContent();
            String webServiceResponse2 = nodeLst2.item(0).getTextContent();
            System.out.println("*** The response from the web service call is : " + webServiceResponse);
            System.out.println("*** The reason from the web service call is: " + webServiceResponse2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Document parseXmlFile(String in) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  //get document builder factory
            DocumentBuilder db = dbf.newDocumentBuilder();                      //create new document builder
            InputSource is = new InputSource(new StringReader(in));             //pass in input source from string reader
            return db.parse(is);
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
} 

我想更接近这种格式

@Test
@RestAssuredMethod(config = "src/test/resources/config/sampleRest.json")
public void getResponse() throws IOException {
    Response response3 = given().log().all()
            .when().get("updateFiles/")
            .then().assertThat()
            .statusCode(HttpStatus.SC_OK) //SC_OK = 200
            .body("status[0].model", equalTo("Success"))
            .header("Content-Type", containsString("application/json"))
            .log().all(true)
            .extract().response();

    String firstResponse = response3.jsonPath().get("status[0].model");
    asserts.assertEquals(firstResponse, "SUCCESS", "Response does not equal SUCCESS");

    List allResponses = response3.jsonPath().getList("status[0].model");
    System.out.println("**********" + favoriteModels);
    asserts.assertTrue(allResponses.contains("Success"), "There are no success responses");
}

编辑:这是我正在尝试使用完整 REST 方法集成的工作发送/接收响应:

package com.chillyfacts.com;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Send_XML_Post_Request {
    public static void main(String[] args) {
        try {
            String url = "<enterEndpointHere>";
            URL obj = new URL(url);
            HttpURLConnection HTTPConnection = (HttpURLConnection) obj.openConnection();

            HTTPConnection.setRequestMethod("POST");
            HTTPConnection.setRequestProperty("Content-Type","text/xml; charset=utf-8");
            HTTPConnection.setDoOutput(true);
            String xml = "<pasteXMLRequestHere>"
            DataOutputStream writeRequest = new DataOutputStream(HTTPConnection.getOutputStream());
            writeRequest.writeBytes(xml);
            writeRequest.flush();
            writeRequest.close();

            String responseStatus = HTTPConnection.getResponseMessage();
            System.out.println(responseStatus);
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    HTTPConnection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            System.out.println("\n **** RESPONSE FROM ENDPOINT RECEIVED ****: \n\n" + response.toString() + "\n\n *************** END OF RESPONSE *************** \n");
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

标签: javaxmlxmlhttprequestresponserest

解决方案


推荐阅读