import java.net.*;
import java.io.*;
import java.util.List;
import java.util.Arrays;
public class WebServiceCaller {
private static final String callURL =
"http://%s/Web-Services/%s";
private static final String envelope =
"<?xml version='1.0'?>" +
"<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'" +
" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
" xmlns:soapenc='http://schemas.xmlsoap.org/soap/encoding/'" +
" xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
" <env:Header/>" +
" <env:Body env:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>" +
" <m:%s xmlns:m='http://%s'>%s</m:%1$s>" +
" </env:Body>" +
"</env:Envelope>";
private WebServiceCaller() {
//do not instantiate
}
/*
Example:
ip = 10.211.10.21:6202
ws = InventoryWebService
wsMethod = getInventoryTag
wsClass = inventorytag.wgs.ws.guardian.com
content = List{D1814898, 00000000.00B2.17, en, en_US, en_US, en_US}
<string xsi:type='xsd:string'>
*/
public static String call(String ip, String ws, String wsMethod, String wsClass, List<String> content)
throws Exception {
StringBuilder sb = new StringBuilder();
String tag = "string";
for (int i = 0; i < content.size(); i++) {
sb.append("<").append(tag).append(" xsi:type='xsd:string'>").append(content.get(i))
.append("</").append(tag).append(">");
tag = "string" + i;
}
URL url = new URL(String.format(callURL, ip, ws));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type",
"application/soap+xml; charset=utf-8");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
String env = String.format(envelope, wsMethod, wsClass, sb);
wr.write(env);
wr.flush();
sb.setLength(0);
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.
getInputStream()));
for (String line = rd.readLine(); line != null; line = rd.readLine()) {
sb.append(line);
}
wr.close();
rd.close();
return sb.toString();
} else {
throw new Exception("ErrorCode: " + conn.getResponseCode() + "\nURL: " + url +
"\nEnvelope: \n" + env);
}
}
//for testing
public static void main(String... args) throws Exception {
List<String> content = Arrays.asList(
new String[]{"D1814898", "00000000.00B2.17", "en", "en_US", "en_US", "en_US"});
System.out.println(call("666.666.666.666:6666", "InventoryTagWebService", "getInventoryTag",
"inventorytag.meinefirma.com", content));
}
}