如何解决使用带有 REST 方法的 Java 代码从 API (Insomnia / SoapUI) 发送 XML 请求和读取 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);
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。