Simple guide to efficiently create Java clients for enterprise web-services

XML-based SOAP web service call

For SOAP, below is a sample XML request for fetching details of last purchases made by a customer at a Walmart store outlet somewhere in Birnin Zana, the capital city of Wakanda. The parameter names have a prefix (“abc”) so as to avoid conflict when reusing the same parameter name multiple times in request body. For e.g., to fetch combined purchases made by the customer on that date at Walmart and a Walmart subsidiary like Sam’s Club using one api call the user will have to reuse the parameter names like endPointFolder twice in the same request (once for Walmart, once for Sam’s Club). Having different prefixes (“abc” and say “def”) in the two tags will help preserve the xml document structure.

<SOAP-ENV:Envelope xmlns:SOAP-ENV=”http://schemas.xmlsoap.org/soap/envelope/" xmlns:abc=”http://testws.ws.custdatarepo.global.org/testwebservices" xmlns:serv=”http://services.ws.custdatarepo.global.org">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<sample:testwsxml>
<sample:testws
xmlns:serv=”http://services.ws.custdatarepo.global.org">
<abc:endPointFolder>Walmart</abc:endPointFolder>
<abc:customerStatus/>
<abc:storeCity>BirninZana</abc:storeCity>
<abc:storeCountry>Wakanda</abc:storeCountry>
<abc:storeLocation>BroadStreet</abc:storeLocation>
<abc:customerMobileNo>5550123</abc:customerMobileNo>
<abc:dateOfVisit>03–30–2021</abc:dateOfVisit>
<abc:wsConnectionID>99999999</abc:wsConnectionID>
</sample:testws>
</sample:testwsxml>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPPart;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPConnection;
import javax.net.ssl.*;
public class client {public static void main(String[] args) {SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection connection = soapConnectionFactory.createConnection();
String endpointUrl = soap_endpoint.toString(); //https://custdatarepo.global.org/test?wsdl
SOAPMessage request = MessageFactory.newInstance().createMessage();
SOAPPart part=request.getSOAPPart();
SOAPEnvelope envelope=part.getEnvelope();
envelope.addNamespaceDeclaration(“abc”,”http://testws.ws.custdatarepo.global.org/testwebservices");
envelope.addNamespaceDeclaration(“serv”,”http://services.ws.custdatarepo.global.org");
SOAPBody body=envelope.getBody();
SOAPBodyElement element=body.addBodyElement(envelope.createName(“testwsxml”,”sample”,””));
SOAPBodyElement element1=element.addChildElement(“testws”,”sample”);
element1.addChildElement(“endPointFolder”,”abc”).addTextNode(“Walmart”);
element1.addChildElement(“customerStatus”,”abc”);
element1.addChildElement(“storeCity”,”abc”).addTextNode(“BirninZana”);
element1.addChildElement(“storeCountry”,”abc”).addTextNode(“Wakanda”);
element1.addChildElement(“storeLocation”,”abc”).addTextNode(“BroadStreet”);
element1.addChildElement(“customerMobileNo”,”abc”).addTextNode(“5550123”);
element1.addChildElement(“dateOfVisit”,”abc”).addTextNode(“03–30–2021”);
element1.addChildElement(“wsConnectionID”,”abc”).addTextNode(“99999999”);
request.writeTo(fout1);
fout1.close();
System.out.println(“Request :: “+request.toString());
SOAPMessage response = connection.call(request, endpointUrl);
SOAPBody soapBody = response.getSOAPBody();
}}
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
NodeList nodes = soapBody.getElementsByTagName(“io:numberOfItems”);
Node node = nodes.item(0);
String numberofitems = node != null ? node.getTextContent() : “”;
System.out.println(“numberofitems :: “+numberofitems);
import javax.xml.soap.MimeHeaders;
MimeHeaders headers = request.getMimeHeaders();
String soapaction=”http://testws.ws.custdatarepo.global.org/testwebservices/getcustdata";
headers.addHeader(“SOAPAction”, soapaction);
request.saveChanges();
import javax.xml.soap.AttachmentPart;
int numOfAttachments = response.countAttachments();
Iterator attachmentIterator = response.getAttachments();
StringBuilder buf = new StringBuilder(“Number of attachments: “);
buf.append(numOfAttachments);
int count = 1;
while (attachmentIterator.hasNext()){
AttachmentPart attachment = (AttachmentPart)
attachmentIterator.next();
buf.append(“ | #”).append(count);
buf.append(“ | Content Location:
“).append(attachment.getContentLocation());
buf.append(“ | Content Id: “).append(attachment.getContentId());
buf.append(“ | Content Size: “).append(attachment.getSize());
buf.append(“ | Content Type:
“).append(attachment.getContentType());
buf.append(“ | Content String: “).append(attachment.toString());
count++;
//writing the file to particular system path (C drive ,D drive)
FileOutputStream out_file = new FileOutputStream(new
File(“D:\\tmp\\fresponse_1024.zip”));
out_file.write(attachment.getRawContentBytes());
out_file.close();
System.out.println(“buf : “+buf.toString());
}

JSON-based REST API call

For the same data fetching request above, let us say below is a JSON request that needs to be POSTed to the REST api endpoint:

{
“Request”: {
“Header”: { “subHeader”: {
“RequestUUID”: “1563745499”,
“ContentType”: “application/json”,
“ApiKey”: “someApiKey”
} },
“Body”: {
“getCustData”: {“RequestBody”:{
“endPointFolder”: “Walmart”,
“storeCity”: “BirninZana”,
“storeCountry”: “Wakanda”,
“storeLocation”: “BroadStreet”,
“customerMobileNo”: “5550123”,
“dateofVisit”: “03–30–2021”,
“wsConnectionID”: “99999999”
} }
}
}
}
import javax.json.JsonObject;
import javax.json.JsonArray;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;
import javax.json.JsonReader;
public class client {public static void main(String[] args) {JsonObjectBuilder subheaderbuilder=javax.json.Json.createObjectBuilder();
Long requuid=Long.valueOf((new Date()).getTime());
String requestuuid=requuid.toString();
subheaderbuilder.add(“RequestUUID”,requestuuid).add(“ContentType”,”application/json”).add(“ApiKey”,”someApiKey”);
JsonObjectBuilder headerbuilder=javax.json.Json.createObjectBuilder();
headerbuilder.add(“subHeader”, subheaderbuilder);
JsonObjectBuilder requestBodybuilder=javax.json.Json.createObjectBuilder();
requestBodybuilder.add(“endPointFolder”,”Walmart”).add(“storeCity”,”BirninZana”).add(“storeCountry”,”Wakanda”).add(“storeLocation”,”BroadStreet”).add(“customerMobileNo”,”5550123").add(“dateofVisit”,”03–30–2021").add(“wsConnectionID”,”99999999");
JsonObjectBuilder getcustdatabuilder=javax.json.Json.createObjectBuilder();
getcustdatabuilder.add(“RequestBody”, requestBodybuilder);
JsonObjectBuilder bodybuilder=javax.json.Json.createObjectBuilder();
bodybuilder.add(“getCustData”, getcustdatabuilder);
JsonObjectBuilder requestbuilder=javax.json.Json.createObjectBuilder();
requestbuilder.add(“Header”,headerbuilder).add(“Body”,bodybuilder);
JsonObjectBuilder finalrequestbuilder=javax.json.Json.createObjectBuilder();
finalrequestbuilder.add(“Request”, requestbuilder);
JsonObject request=finalrequestbuilder.build();
String requestcontent = request.toString();
System.out.println(“Request content :”+ requestcontent);
URL url = new URL(“https://custdatarepo.global.org/api/test");
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
System.out.println(“Connection established successfully”);
con.setRequestMethod(“POST”);
con.setRequestProperty(“Content-Type”, “application/json; utf-8”);
con.setRequestProperty(“Accept”, “application/json”);
con.setDoOutput(true);
try(OutputStream os = con.getOutputStream()){
byte[] input = request.toString().getBytes(“utf-8”);
os.write(input, 0, input.length);
}catch(Exception e){
e.printStackTrace();
System.out.println(“Error Message :: “+e.getMessage());
}
try(BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), “utf-8”))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
String responsefull=response.toString();
JsonReader reader=javax.json.Json.createReader(new
StringReader(responsefull));
JsonObject responseObj=reader.readObject();
reader.close(); //next parse this json object to fetch specific
parameter values
}catch(Exception e){
e.printStackTrace();
System.out.println(“Error Message :: “+e.getMessage());
}
}}
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.KeyManagementException;
public class client {
.....
private static void disableSslVerification() {
try{
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {...
disableSslVerification();
...
}}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Arpan Roy

Arpan Roy

I write about technology-related ideas and tools I’ve experimented with. I enjoy reading up on new software, space and fiction written by old British ladies.