使用java代码和REST方法发送XML请求,并从API(API/SoapUI)读取XML响应
目标概述:(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);
}
}
}
共 (0) 个答案