posting XML request in java
Here’s an example how to do it with java.net.URLConnection :
String url = "http://example.com"; String charset = "UTF-8"; String param1 = URLEncoder.encode("param1", charset); String param2 = URLEncoder.encode("param2", charset); String query = String.format("param1=%s¶m2=%s", param1, param2); URLConnection urlConnection = new URL(url).openConnection(); urlConnection.setUseCaches(false); urlConnection.setDoOutput(true); // Triggers POST. urlConnection.setRequestProperty("accept-charset", charset); urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded"); OutputStreamWriter writer = null; try < writer = new OutputStreamWriter(urlConnection.getOutputStream(), charset); writer.write(query); // Write POST query string (if any needed). >finally < if (writer != null) try < writer.close(); >catch (IOException logOrIgnore) <> > InputStream result = urlConnection.getInputStream(); // Now do your thing with the result. // Write it into a String and put as request attribute // or maybe to OutputStream of response as being a Servlet behind `jsp:include`.
Solution 2
This example post an xml file, it depends on Jakarta HttpClient API (jakarta.apache.org)
import java.io.File; import java.io.FileInputStream; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.InputStreamRequestEntity; import org.apache.commons.httpclient.methods.PostMethod; /** * This is a sample application that demonstrates * how to use the Jakarta HttpClient API. * * This application sends an XML document * to a remote web server using HTTP POST * * @author Sean C. Sullivan * @author Ortwin Glück * @author Oleg Kalnichevski */ public class PostXML < /** * * Usage: * java PostXML http://mywebserver:80/ c:\foo.xml * * @param args command line arguments * Argument 0 is a URL to a web server * Argument 1 is a local filename * */ public static void main(String[] args) throws Exception < if (args.length != 2) < System.out.println( "Usage: java -classpath [-Dorg.apache.commons."+ "logging.simplelog.defaultlog=]" + " PostXML ]"); System.out.println(" - must contain the "+ "commons-httpclient.jar and commons-logging.jar"); System.out.println(" - one of error, "+ "warn, info, debug, trace"); System.out.println(" - the URL to post the file to"); System.out.println(" - file to post to the URL"); System.out.println(); System.exit(1); > // Get target URL String strURL = args[0]; // Get file to be posted String strXMLFilename = args[1]; File input = new File(strXMLFilename); // Prepare HTTP post PostMethod post = new PostMethod(strURL); // Request content will be retrieved directly // from the input stream // Per default, the request content needs to be buffered // in order to determine its length. // Request body buffering can be avoided when // content length is explicitly specified post.setRequestEntity(new InputStreamRequestEntity( new FileInputStream(input), input.length())); // Specify content type and encoding // If content encoding is not explicitly specified // ISO-8859-1 is assumed post.setRequestHeader( "Content-type", "text/xml; charset=ISO-8859-1"); // Get HTTP client HttpClient httpclient = new HttpClient(); // Execute request try < int result = httpclient.executeMethod(post); // Display status code System.out.println("Response status code: " + result); // Display response System.out.println("Response body: "); System.out.println(post.getResponseBodyAsString()); >finally < // Release current connection to the connection pool // once you are done post.releaseConnection(); >> >
Solution 3
Use InputStreamEntity . I used httpclient 4.2.1.
HttpPost httppost = new HttpPost(url); InputStream inputStream=new ByteArrayInputStream(xmlString.getBytes());//init your own inputstream InputStreamEntity inputStreamEntity=new InputStreamEntity(inputStream,xmlString.getBytes()); httppost.setEntity(inputStreamEntity);
Solution 4
Warning this code is 5+ years old. I did some modfying for this post and never tested it. Hopefully it helps.
Post XML (data) to a server and downlod the resp:
public int uploadToServer(String data) throws Exception < OutputStream os; URL url = new URL("someUrl"); HttpURLConnection httpConn= (HttpURLConnection) url.openConnection(); os = httpConn.getOutputStream(); BufferedWriter osw = new BufferedWriter(new OutputStreamWriter(os)); osw.write(data); osw.flush(); osw.close(); return httpConn.getResponseCode(); >public String downloadFromServer() throws MalformedURLException, IOException < String returnString = null; StringBuffer sb = null; BufferedInputStream in; //set up httpConn code not included same as previous in = new BufferedInputStream(httpConn.getInputStream()); int x = 0; sb = new StringBuffer(); while ((x = in.read()) != -1) < sb.append((char) x); >in.close(); in = null; if (httpConn != null) < httpConn.disconnect(); >return sb.toString(); >
int respCode = uploadToServer(someXmlData); if (respCode == 200)
Java: How to send a XML request?
If you are looking to do an HTTP POST, then you could use the java.net.* APIs in Java SE:,My guess is that the protocol you are using is HTTP(S) and you have to do a POST with your XML request, but this is just an educated(?) guess., Why hooks are the best thing to happen to React , Problem regarding the use of determiners in the English language
If you are looking to do an HTTP POST, then you could use the java.net.* APIs in Java SE:
Answer by Jaliyah Phelps
The following example demonstrates how to use the HttpURLConnection to post the XML request packet.,Java — How to post XML request using HttpURLConnection,Jackson API — Collection serialization and deserialization example,This website is developed to teach java programming and java web technologies with short and simple examples. If you liked tutorials and examples on this website, please follow us on
RestXmlHttpClient.java
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class RestXmlHttpClient < public static void main(String[] args) throws IOException < String request = "Sunil "; URL url = new URL("http://localhost:8080/myservice"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Set timeout as per needs connection.setConnectTimeout(20000); connection.setReadTimeout(20000); // Set DoOutput to true if you want to use URLConnection for output. // Default is false connection.setDoOutput(true); connection.setUseCaches(true); connection.setRequestMethod("POST"); // Set Headers connection.setRequestProperty("Accept", "application/xml"); connection.setRequestProperty("Content-Type", "application/xml"); // Write XML OutputStream outputStream = connection.getOutputStream(); byte[] b = request.getBytes("UTF-8"); outputStream.write(b); outputStream.flush(); outputStream.close(); // Read XML InputStream inputStream = connection.getInputStream(); byte[] res = new byte[2048]; int i = 0; StringBuilder response = new StringBuilder(); while ((i = inputStream.read(res)) != -1) < response.append(new String(res, 0, i)); >inputStream.close(); System.out.println("Response= " + response.toString()); > >
Answer by Yahir Tang
In the video I have shown how you can create an XML request and send to an endpoint URL, Then receive the response from the server. You can send both get request and post request with below examples.,Press enter to see results or esc to cancel.,Send_XML_Post_Request_1.java and Send_XML_Post_Request_2.java are 2 different example codes., Create shortcut to change the IP address of the PC
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_1 < public static void main(String[] args) < try < String url = "http://www.holidaywebservice.com/HolidayService_v2/HolidayService2.asmx?op=GetHolidaysAvailable"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type","application/soap+xml; charset=utf-8"); String countryCode="Canada"; String xml = "" + " " + " " + " " + " "+countryCode+" " + " " + " " + " "; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(xml); wr.flush(); wr.close(); String responseStatus = con.getResponseMessage(); System.out.println(responseStatus); BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) < response.append(inputLine); >in.close(); System.out.println("response:" + response.toString()); > catch (Exception e) < System.out.println(e); >> >
Output on Eclipse console
OK response:NEW-YEARS-DAY-ACTUAL
New Year's Day NEW-YEARS-DAY-OBSERVED
New Year's Day DAY-AFTER-NEW-YEARS-DAY
Day After New Year's Day (QC) EPIPHANY
Epiphany QUEBEC-FLAG-DAY
Quebec Flag Day GROUNDHOG-DAY
Groundhog Day VALENTINES-DAY
Valentine's Day
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_2 < public static void main(String[] args) < try < String url = "http://www.holidaywebservice.com/HolidayService_v2/HolidayService2.asmx?op=GetCountriesAvailable"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type","application/soap+xml; charset=utf-8"); String xml = "" + " " + " " + " " + " "; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(xml); wr.flush(); wr.close(); String responseStatus = con.getResponseMessage(); System.out.println(responseStatus); BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) < response.append(inputLine); >in.close(); System.out.println("response:" + response.toString()); > catch (Exception e) < System.out.println(e); >> >
Output on Eclipse console,
OK response:Canada
Canada GreatBritain
Great Britain and Wales IrelandNorthern
Northern Ireland IrelandRepublicOf
Republic of Ireland Scotland
Scotland UnitedStates
United States
Answer by Everleigh O’Donnell
In our previous example, we handled an XML request, but replied with a text/plain response. Let’s change it to send back a valid XML HTTP response:,Handling and serving XML requests,Note: This way, a 400 HTTP response will be automatically returned for non-XML requests.,Accessing an SQL database
By default, an action uses an any content body parser, which you can use to retrieve the body as XML (actually as a org.w3c.Document ):
public Result sayHello(Http.Request request) < Document dom = request.body().asXml(); if (dom == null) < return badRequest("Expecting Xml data"); >else < String name = XPath.selectText("//name", dom); if (name == null) < return badRequest("Missing parameter [name]"); >else < return ok("Hello " + name); >> >
Of course it’s way better (and simpler) to specify our own BodyParser to ask Play to parse the content body directly as XML:
@BodyParser.Of(BodyParser.Xml.class) public Result sayHelloBP(Http.Request request) < Document dom = request.body().asXml(); if (dom == null) < return badRequest("Expecting Xml data"); >else < String name = XPath.selectText("//name", dom); if (name == null) < return badRequest("Missing parameter [name]"); >else < return ok("Hello " + name); >> >
You can test it with curl on the command line:
curl --header "Content-type: application/xml" --request POST --data 'Guillaume ' http://localhost:9000/sayHello
HTTP/1.1 200 OK Content-Type: text/plain; charset=utf-8 Content-Length: 15 Hello Guillaume
In our previous example, we handled an XML request, but replied with a text/plain response. Let’s change it to send back a valid XML HTTP response:
@BodyParser.Of(BodyParser.Xml.class) public Result replyHello(Http.Request request) < Document dom = request.body().asXml(); if (dom == null) < return badRequest("Expecting Xml data"); >else < String name = XPath.selectText("//name", dom); if (name == null) < return badRequest("Missing parameter [name] ") .as("application/xml"); > else < return ok("Hello " + name + " ").as("application/xml"); > > >
HTTP/1.1 200 OK Content-Type: application/xml; charset=utf-8 Content-Length: 46 Hello Guillaume
Answer by Ben Dunn
Opinions expressed by DZone contributors are their own.
// This is a working example of POSTing a string (representing a block of XML) to a web server try < URL url = new URL( argUrl ); URLConnection con = url.openConnection(); // specify that we will send output and accept input con.setDoInput(true); con.setDoOutput(true); con.setConnectTimeout( 20000 ); // long timeout, but not infinite con.setReadTimeout( 20000 ); con.setUseCaches (false); con.setDefaultUseCaches (false); // tell the web server what we are sending con.setRequestProperty ( "Content-Type", "text/xml" ); OutputStreamWriter writer = new OutputStreamWriter( con.getOutputStream() ); writer.write( requestXml ); writer.flush(); writer.close(); // reading the response InputStreamReader reader = new InputStreamReader( con.getInputStream() ); StringBuilder buf = new StringBuilder(); char[] cbuf = new char[ 2048 ]; int num; while ( -1 != (num=reader.read( cbuf ))) < buf.append( cbuf, 0, num ); >String result = buf.toString(); System.err.println( "\nResponse from server after POST:\n" + result ); > catch( Throwable t )
Sending XML Request with REST-assured
Learn to send requests with XML request body and validate the response using REST-assured APIs.
1. By Parsing Custom Object to XML
1.1. Parsing Java Object to XML
If we can take the help of libraries such as Jackson or JAXB, for converting a custom object into XML String, it should be the preferred way. It helps in making the code more readable and manageable.
For example, if we have an API that takes the following request:
HTTP POST /users lokesh admin@howtodoinjava.com male active
We can create a Java object UserObject and annotate it with Jackson annotations so that it parses to the desired XML string.
@JacksonXmlRootElement(localName = "user") class UserObject
Now, we can use Jackson’s XmlMapper.writeValueAsString() method to get the XML string for the UserDTO instance. This will generate the XML as given previously.
UserObject newUser = new UserObject(); newUser.setName("lokesh"); newUser.setEmail("admin@howtodoinjava.com"); newUser.setGender("male"); newUser.setStatus("active"); String newUserXml = new XmlMapper().writeValueAsString(newUser);
1.2. Sending Request with REST-assured
Sending the XML request body is very simple. We need to set the content type to “application/xml” (or any other custom mediatype, if any) and then pass the XML string to the given().body(xml) method.
A complete example of sending the XML request to a POST API is:
@Test public void createUserWithJSONObject_thenSuccess() throws JSONException, JsonProcessingException < UserObject newUser = new UserObject(); newUser.setName("lokesh"); newUser.setEmail("admin@howtodoinjava.com"); newUser.setGender("male"); newUser.setStatus("active"); String newUserXml = new XmlMapper().writeValueAsString(newUser); given() .body(newUserXml) .contentType("application/xml") .queryParam("access-token", "xxxx") .when() .post("/users") .then() .statusCode(201) .body("id", notNullValue()) .body("name", equalTo("lokesh")) .body("gender", equalTo("male")) .body("status", equalTo("active")) .body("email", equalTo("admin@howtodoinjava.com")) .log().all(); >
2. By Reading XML from File
In automation testing, we may not have created DTO objects, and we may need to rely on hardcoded XML strings. In this case, creating such XML strings in separate XML files that are API specific is always better.
We read the XML file for each API and post its content to the API. In this approach, only obtaining the XML string is different and invoking the API is the same as the previous example.
File newUserXmlFile = new File("src/test/resources/requests/newUser.xml"); given() .body(newUserXmlFile) . .when() .post("/users") .then() . ;
This short tutorial taught us to pass the XML requests to REST APIs using REST-assured. We learned to get the XML request strings from either custom Java objects or XML files in the filesystem. Then we learned to pass the XML to the API and validate the response.