Apache CXF: JAX-RS Restful web service using JAXB + XML example

In this article, we will learn and implement a JAX-RS Restful web service using JAXB. Although there are various types of input/output formats can be used for request/response for web service interaction, but in this particular example we will use XML (eXtensible Markup Language)

JAX-RS specification supports the conversion of Java objects to XML and vicey-versay on the fly with the help of JAXB i.e.; marshalling/un-marshalling

When it is finalized to use XML then start designing your XML Schema Definition (XSD) for your service and call the help of JAXB Maven plugin to generate java-sources, as it is considered standard. So, before starting to develop a web service it is important to spend good amount of time in writing XSD for your service

In this example, we will implement a service covering all CURD operations using annotations such as @GET, @POST, @PUT and @DELETE. Also, we will use @Consumes, @Produces and MediaType annotations to send & receive XML for the web service request/response

NOTE: No need to add any extra libraries or any dependency into pom.xml to support JAXB, as it comes shipped with JDK 7.0

Annotation Used

  • @Path (javax.ws.rs.Path)
  • @GET (javax.ws.rs.GET)
  • @POST (javax.ws.rs.POST)
  • @PUT (javax.ws.rs.PUT)
  • @DELETE (javax.ws.rs.DELETE)
  • @PathParam (javax.ws.rs.PathParam)
  • @Consumes (javax.ws.rs.Consumes)
  • @Produces (javax.ws.rs.Produces)
  • @Service (org.springframework.stereotype.Service)
  • MediaType (javax.ws.rs.core.MediaType)

Technology Used

  • Java 1.7
  • Eclipse Luna IDE
  • Spring-4.0.0-RELEASE
  • Apache-CXF-3.0.0
  • Apache Maven 3.2.1
  • Apache Tomcat 7.0.54

Mavenize or download required jars

Add Apache-CXF-3.0.0 and Spring-4.0.0-RELEASE dependencies to pom.xml

<dependencies>
		<!-- Apache CXF -->
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-frontend-jaxrs</artifactId>
			<version>${cxf.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-transports-http</artifactId>
			<version>${cxf.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-transports-http-jetty</artifactId>
			<version>${cxf.version}</version>
		</dependency>

		<!-- Spring framework -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
</dependencies>

Folks who aren’t familiar with Maven concepts or don’t require maven for their project, can download the below jars individually from the spring site or maven repository and include them in the classpath

JAXB – Generating java source files from XSD

Steps to generate java-sources from XML Schema Definition (XSD)

  • configure JAXB Maven plugin in pom.xml
  • write well-defined XSD for your service
  • use maven command “mvn generate-sources” to generate java source files

Configure JAXB Maven plugin

<!-- JAXB plugin to generate-sources from XSD -->
<plugin>
	<groupId>org.codehaus.mojo</groupId>
	<artifactId>jaxb2-maven-plugin</artifactId>
	<version>1.5</version>
	<executions>
		<execution>
			<goals>
				<goal>xjc</goal><!-- xjc/generate -->
			</goals>
			<configuration>
				<outputDirectory>${basedir}/generated/java/source</outputDirectory>
				<schemaDirectory>${basedir}/src/main/resources/com/apache/cxf/xml/service/entities
				</schemaDirectory>
				<schemaFiles>*.xsd</schemaFiles>
				<schemaLanguage>XMLSCHEMA</schemaLanguage>
				<extension>true</extension>
				<args>
					<arg>-XtoString</arg>
				</args>
				<plugins>
					<plugin>
						<groupId>org.jvnet.jaxb2_commons</groupId>
						<artifactId>jaxb2-basics</artifactId>
						<version>0.6.4</version>
					</plugin>
				</plugins>
			</configuration>
		</execution>
	</executions>
</plugin>

Player.xsd

Below XSD contains two elements with name “PlayerType” and “PlayerListType”

  • PlayerType contains four attributes namely playerId, name, age and matches
  • PlayerListType which returns list of PlayerType
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	targetNamespace="http://benchresources.in/cdm/Player" xmlns:tns="http://benchresources.in/cdm/Player"
	elementFormDefault="qualified">

	<xsd:element name="PlayerType">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element ref="tns:Player" minOccurs="0" maxOccurs="unbounded" />
			</xsd:sequence>
		</xsd:complexType>
	</xsd:element>

	<xsd:element name="Player">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element name="playerId" type="xsd:int" />
				<xsd:element name="name" type="xsd:string" />
				<xsd:element name="age" type="xsd:int" />
				<xsd:element name="matches" type="xsd:int" />
			</xsd:sequence>
		</xsd:complexType>
	</xsd:element>
</xsd:schema>

Run mvn generate-sources

Look at the generated java source files in the generated folder

PlayerType.java

package in.benchresources.cdm.player;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "playerId",
    "name",
    "age",
    "matches"
})
@XmlRootElement(name = "PlayerType")
public class PlayerType {

    protected int playerId;
    @XmlElement(required = true)
    protected String name;
    protected int age;
    protected int matches;

    public int getPlayerId() {
        return playerId;
    }
    public void setPlayerId(int value) {
        this.playerId = value;
    }
    public String getName() {
        return name;
    }
    public void setName(String value) {
        this.name = value;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int value) {
        this.age = value;
    }
    public int getMatches() {
        return matches;
    }
    public void setMatches(int value) {
        this.matches = value;
    }
}

PlayerListType.java

package in.benchresources.cdm.player;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "playerType"
})
@XmlRootElement(name = "PlayerListType")
public class PlayerListType {

    @XmlElement(name = "PlayerType")
    protected List<PlayerType> playerType;
    public List<PlayerType> getPlayerType() {
        if (playerType == null) {
            playerType = new ArrayList<PlayerType>();
        }
        return this.playerType;
    }
}

Directory Structure

Before moving on, let us understand the directory/package structure once you create project in Eclipse IDE
Maven has to follow certain directory structure

  • src/test/java –> test related files, mostly JUnit test cases
  • src/main/java –> create java source files under this folder
  • src/main/resources –> all configuration files placed here
  • generated/java/source –> generated java source files are placed here
  • Maven Dependencies or Referenced Libraries –> includes jars in the classpath
  • WEB-INF under webapp –> stores web.xml & other configuration files related to web application

Project Structure (Package Explorer view in Eclipse)

1_ApacheCXF-XML-IO_Project_Structure_In_Eclipse

Jars Libraries Used in the Project (Maven Dependencies)

2_ApacheCXF-XML-IO_Jars_In_Classpath

Web application

For any web application, entry point is web.xml which describes how the incoming http requests are served / processed. Further, it describes about the global-context and local-context param (i.e.; <context-param> & <init-param>) for loading files particular to project requirements & contains respective listener

With this introduction, we will understand how we configured web.xml for Apache CXF JAX-RS Restful web service

web.xml (the entry point –> under WEB-INF)

This web.xml file describes,

  • like any JEE web framework register org.apache.cxf.transport.servlet.CXFServletwith servlet container
  • all http requests with URL pattern “/services/*” will be sent to the registered servlet called “CXFServlet” (org.apache.cxf.transport.servlet.CXFServlet)
  • <context-param> with its attributes describes the location of the “apache-cxf-service.xml” file from where it has to be loaded. We will discuss briefly about this file
  • <welcome-file-list> files under this tag is the start-up page

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<display-name>ApacheCXF-XML-IO</display-name>

	<!-- Apache CXF -->
	<servlet>
		<servlet-name>CXFServlet</servlet-name>
		<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>CXFServlet</servlet-name>
		<url-pattern>/services/*</url-pattern>
	</servlet-mapping>

	<!-- web context param -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>WEB-INF/apache-cxf-services.xml</param-value>
	</context-param>

	<!-- listener -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- welcome file list -->
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

Apache CXF services

Apache CXF comes with spring based configuration, so it is easy to register beans in the spring container much like we do any bean in spring application. CXFServlet receives the incoming http requests and invokes corresponding registered beans in according to http url path

NOTE: For this Restful JAX-RS application, we are using Spring annotations to define/register beans in the spring container thereby avoiding lot of boilerplate code to write

This apache-cxf-services.xml describes,

  • <context:annotation-config /> to activate annotation on the registered beans with application context
  • <context:component-scan base-package=”” /> tag scans all classes & sub-classes under the value of base-package attribute and register them with Spring container
  • <jaxrs:server /> defines which service bean to be invoked for the incoming http requests. In this case, any wild card pattern “/” will invoke “playerService” which is registered as service bean using @Service(“playerService”) annotation (on top of the PlayerServiceImpl java class)
  • NOTE: For two different beans we can have two different url-pattern(address) like
		<jaxrs:server id="restContainer" address="/">
			<jaxrs:serviceBeans>
				<ref bean="playerService" />
			</jaxrs:serviceBeans>
		</jaxrs:server>
		
		<jaxrs:server id="twotest" address="/two">
			<jaxrs:serviceBeans>
				<ref bean="testService" />
			</jaxrs:serviceBeans>
		</jaxrs:server>

apache-cxf-services.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
	xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
	http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- to turn on annotation wiring == turns on only the registered beans
		through ApplicationContext -->
	<context:annotation-config />

	<!-- scans and register beans using annotation-config (metadata) -->
	<context:component-scan base-package="com.apache.cxf.xml.service" />

	<jaxrs:server id="restContainer" address="/">
		<jaxrs:serviceBeans>
			<ref bean="playerService" />
		</jaxrs:serviceBeans>
	</jaxrs:server>
</beans>

 

Let’s see coding in action

 

URL Pattern

Http URL for any common web application is http://<server>:<port>/<context-root>/<from_here_application_specific_path>

In our example, we are going to deploy the war into Tomcat 7.0 server so our server & port are localhost and 8080 respectively. Context root is the project name i.e.; ApacheCXF-XML-IO. Initial path for this application is http://localhost:8080/ApacheCXF-XML-IO

We have configured “/services/*” as url-pattern for the CXFServlet in web.xml and at interface-level (or say class-level) path configured is “/player” using @Path annotation. Next respective path for each method annotated with @Path (method-level)

Player Service interface

Defines simple CURD operations

  • @POST          – create/inserts a new resource (new player)
  • @GET           – read/selects internal resource representation based on the playerId
  • @PUT            – update/modifies an internal resource representation (modify player)
  • @DELETE       – delete/removes a resource (delete player)
  • @GET           – retrieves all players (get all players)

Let’s discuss @Produces, @Consumes and MediaType

@Consumes

Define which MIME type is consumed by this method. For this example, exposed methods are restricted to consume only XML data and it is annotated with @Consumes(MediaType.APPLICATION_XML)

@Produces

Define which MIME type it will produce. For this example, exposed methods are restricted to produce only XML data and it is annotated with @Produces(MediaType.APPLICATION_XML)

Most widely used Media Types are

  • MediaType.APPLICATION_XML,
  • MediaType.APPLICATION_JSON,
  • MediaType.TEXT_PLAIN,
  • MediaType.TEXT_XML,
  • MediaType.APPLICATION_FORM_URLENCODED,
  • etc

NOTE: It’s always a good programming practice to do code-to-interface and have its implementation separately

IPlayerService.java

package com.apache.cxf.xml.service;

import in.benchresources.cdm.player.PlayerListType;
import in.benchresources.cdm.player.PlayerType;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/playerservice")
public interface IPlayerService {

	// Basic CRUD operations for Player Service

	// http://localhost:8080/ApacheCXF-XML-IO/services/playerservice/addplayer
	@POST
	@Path("addplayer")
	@Consumes(MediaType.APPLICATION_XML)
	@Produces(MediaType.APPLICATION_FORM_URLENCODED)
	public String createOrSaveNewPLayerInfo(PlayerType playerType);

	// http://localhost:8080/ApacheCXF-XML-IO/services/playerservice/getplayer/239
	@GET
	@Path("getplayer/{id}")
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces(MediaType.APPLICATION_XML)
	public PlayerType getPlayerInfo(@PathParam("id") int playerId);

	// http://localhost:8080/ApacheCXF-XML-IO/services/playerservice/updateplayer
	@PUT
	@Path("updateplayer")
	@Consumes(MediaType.APPLICATION_XML)
	@Produces(MediaType.APPLICATION_FORM_URLENCODED)
	public String updatePlayerInfo(PlayerType player);

	// http://localhost:8080/ApacheCXF-XML-IO/services/playerservice/deleteplayer
	@DELETE
	@Path("deleteplayer")
	@Consumes(MediaType.APPLICATION_XML)
	@Produces(MediaType.APPLICATION_FORM_URLENCODED)
	public String deletePlayerInfo(PlayerType player);

	// http://localhost:8080/ApacheCXF-XML-IO/services/playerservice/getallplayer
	@GET
	@Path("getallplayer")
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces(MediaType.APPLICATION_XML)
	public PlayerListType getAllPlayerInfo();
}

Player Service implementation

Implements above interface. Self explanatory !!

PlayerServiceImpl.java

package com.apache.cxf.xml.service;

import in.benchresources.cdm.player.PlayerListType;
import in.benchresources.cdm.player.PlayerType;

import org.springframework.stereotype.Service;

@Service("playerService")
public class PlayerServiceImpl implements IPlayerService {

	/**
	 * returns a String value with SUCCESS message after adding a player
	 */
	@Override
	public String createOrSaveNewPLayerInfo(PlayerType playerType) {

		// get the player information from formal arguments and inserts into database & return playerId (primary_key)
		return "Player information saved successfully with PLAYER_ID " + 344;
	}

	/**
	 * retrieves a player object based on the playerId supplied in the formal argument using @PathParam
	 */
	@Override
	public PlayerType getPlayerInfo(int playerId) {

		// retrieve player based on the id supplied in the formal argument
		PlayerType getplayer = new PlayerType();
		getplayer.setPlayerId(239);
		getplayer.setName("Virender Sehwag");
		getplayer.setAge(35);
		getplayer.setMatches(102);
		return getplayer;
	}

	/**
	 * returns a String value with SUCCESS message after updating a player
	 */
	@Override
	public String updatePlayerInfo(PlayerType playerType) {

		// update player info & return SUCCESS message
		return "Player information updated successfully";
	}

	/**
	 * returns a String value with SUCCESS message after deleting a player
	 */
	@Override
	public String deletePlayerInfo(PlayerType playerType) {

		// delete player info & return SUCCESS message
		return "Player information deleted successfully";
	}

	/**
	 * retrieves all players stored
	 */
	@Override
	public PlayerListType getAllPlayerInfo() {

		// create a object of type PlayerType which takes player objects in its list
		PlayerListType playerListType = new PlayerListType();

		// player 1 info
		PlayerType playerOne = new PlayerType();
		playerOne.setPlayerId(346);
		playerOne.setName("Mark Taylor");
		playerOne.setAge(49);
		playerOne.setMatches(104);
		playerListType.getPlayerType().add(playerOne); // add to playerListType

		// player 2 info
		PlayerType playerTwo = new PlayerType();
		playerTwo.setPlayerId(356);
		playerTwo.setName("Michael Slater");
		playerTwo.setAge(44);
		playerTwo.setMatches(74);
		playerListType.getPlayerType().add(playerTwo); // add to playerListType

		return playerListType;
	}
}

 

Deployment

  • Run maven command to build the war : mvn clean install (use command prompt or integrated maven in eclipse IDE)
  • Copy the war file from the target folder
  • Paste it into apache tomcat (webapps folder)
  • Start the tomcat server

Test the service !!

 

Testing

There are many ways to do testing

  • Copy the URL of GET service into web browser
  • Advanced REST client from Google Chrome
  • Rest client from Mozilla Firefox Add On
  • Write your own client for example, Java client using httpcomponents from Apache
  • JDK’s in-built classes like HttpURLConnection

 

1. Using RestClient from Mozilla Firefox Add-On

 

First service: @POST (createOrSaveNewPLayerInfo())
URL: http://localhost:8080/ApacheCXF-XML-IO/services/playerservice/addplayer
Request:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PlayerType xmlns="http://benchresources.in/cdm/Player">
	<playerId>344</playerId>
	<name>Ian Healy</name>
	<age>50</age>
	<matches>119</matches>
</PlayerType>

Response:
Player information saved successfully with PLAYER_ID 344

MF_3_ApacheCXF-XML-IO_advanced_rest_client_addplayer

 

Second service: @GET (getPlayerInfo())
URL: http://localhost:8080/ApacheCXF-XML-IO/services/playerservice/getplayer/239
Request: None
Response:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<PlayerType>
	<playerId>239</playerId>
	<name>Virender Sehwag</name>
	<age>35</age>
	<matches>102</matches>
</PlayerType>

MF_4_ApacheCXF-XML-IO_advanced_rest_client_getplayer

 

Third service: @PUT (updatePlayerInfo())
URL: http://localhost:8080/ApacheCXF-XML-IO/services/playerservice/updateplayer
Request:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PlayerType xmlns="http://benchresources.in/cdm/Player">
	<playerId>344</playerId>
	<name>Ian Healy</name>
	<age>50</age>
	<matches>119</matches>
</PlayerType>

Response:
Player information updated successfully
MF_5_ApacheCXF-XML-IO_advanced_rest_client_updateplayer

 

Fourth service: @DELETE (deletePlayerInfo())
URL: http://localhost:8080/ApacheCXF-XML-IO/services/playerservice/deleteplayer
Request:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PlayerType xmlns="http://benchresources.in/cdm/Player">
	<playerId>344</playerId>
	<name>Ian Healy</name>
	<age>50</age>
	<matches>119</matches>
</PlayerType>

Response:
Player information deleted successfully
MF_6_ApacheCXF-XML-IO_advanced_rest_client_deleteplayer

 

Fifth service: @GET (getAllPlayerInfo())
URL: http://localhost:8080/ApacheCXF-XML-IO/services/playerservice/getallplayer
Request: None
Response:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PlayerListType xmlns="http://benchresources.in/cdm/Player">
	<PlayerType>
		<playerId>346</playerId>
		<name>Mark Taylor</name>
		<age>49</age>
		<matches>104</matches>
	</PlayerType>
	<PlayerType>
		<playerId>356</playerId>
		<name>Michael Slater</name>
		<age>44</age>
		<matches>74</matches>
	</PlayerType>
</PlayerListType>

MF_7_ApacheCXF-XML-IO_advanced_rest_client_getallplayer

 

 2. Java Client

This is the different Java client from the one we have seen in the previous articles, where we used Apache’s HttpComponents. For this client, no need to include extra jars or add any dependency in pom.xml as these classes comes shipped with JDK. See the import statements closely

Just tested one service i.e.; /addplayer using HttpURLConnection. Do test other services using this Java client making necessary changes to the requestParams[] array like requestURL, httpMethod, contentType, accept and include correct requestString

TestPlayerService.java

package com.apache.cxf.xml.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.MediaType;

public class TestPlayerService {

	/**
	 * main method to invoke test method
	 * @param args
	 */
	public static void main(String[] args) {

		String requestURL = "http://localhost:8080/ApacheCXF-XML-IO/services/playerservice/addplayer";
		String httpMethod = HttpMethod.DELETE;
		String contentType = MediaType.APPLICATION_XML;
		String accept = MediaType.APPLICATION_FORM_URLENCODED;
		String requestParam = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
				+				"<PlayerType xmlns=\"http://benchresources.in/cdm/Player\">"
				+					"<playerId>344</playerId>"
				+					"<name>Ian Healy</name>"
				+					"<age>50</age>"
				+					"<matches>119</matches>"
				+ 				"</PlayerType>";

		String[] requestParams = {requestURL, httpMethod, requestParam, contentType, accept};

		String responseFromService = testPlayerService(requestParams);
		System.out.println("Response String: " + responseFromService);
	}

	/**
	 * This method uses HttpURLConnection to invoke exposed Restful web service and returns the response string to the calling client
	 * @param requestParams
	 * @return
	 */
	public static String testPlayerService(String[] requestParams) {

		// local variables
		URL url = null;
		HttpURLConnection httpURLConnection = null;
		OutputStreamWriter outputStreamWriter = null;
		String responseMessageFromServer = null;
		String responseXML = null; 

		try {
			url = new URL(requestParams[0]);
			httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setRequestMethod(requestParams[1]);
			httpURLConnection.setRequestProperty("Content-Type", requestParams[3]);
			httpURLConnection.setRequestProperty("Accept", requestParams[4]);
			httpURLConnection.setDoOutput(true);

			outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
			outputStreamWriter.write(requestParams[2]);
			outputStreamWriter.flush();

			System.out.println("Response code: " + httpURLConnection.getResponseCode());

			if (httpURLConnection.getResponseCode() == 200) {

				responseMessageFromServer = httpURLConnection.getResponseMessage();
				System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);
				responseXML = getResponseXML(httpURLConnection);
			}
		}
		catch(Exception  ex){
			ex.printStackTrace();
		}
		finally{
			httpURLConnection.disconnect();
		}
		return responseXML;
	}

	/**
	 * This method is used to get response XML from the HTTP GET Request created for Authorization WireKey
	 * @param httpURLConnection
	 * @return stringBuffer.toString()
	 * @throws IOException
	 */
	private static String getResponseXML(HttpURLConnection httpURLConnection) throws IOException{

		StringBuffer stringBuffer = new StringBuffer();
		BufferedReader bufferedReader = null;
		InputStreamReader inputStreamReader = null;
		String readSingleLine = null;

		try{
			// read the response stream AND buffer the result into a StringBuffer
			inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
			bufferedReader = new BufferedReader(inputStreamReader);

			// reading the XML response content line BY line
			while ((readSingleLine = bufferedReader.readLine()) != null) {
				stringBuffer.append(readSingleLine);
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
		finally{
			// finally close all operations
			bufferedReader.close();
			httpURLConnection.disconnect();
		}
		return stringBuffer.toString();
	}
}

Output in Console

Response code: 200
ResponseMessageFromServer: OK
Response String: Player information saved successfully with PLAYER_ID 344

Conclusion: With the help of JAXB, XML can be used to exchange the request/response in Restful web service. In the next article, we will see how we can use JSON to exchange the request/response in Restful web service

Download project

ApacheCXF-XML-IO (9kB)

Happy Coding !!
Happy Learning !!

Apache CXF: JAX-RS Restful web service using JAXB + JSON example
Apache CXF: JAX-RS Restful web service using @HeaderParam/@Context annotation