Invoking Webservice Methods from Java

This is my helper method for invoking webservices from java. One bonus perk is that this handles the exception when we are using self signed certificates by providing our own HostnameVerifier. This could be more generalized but all I needed was to invoke this one server.

	/**
	 * Invoke webservice to retrive data
	 * 
	 * @param <T>
	 *            Return type the service will return
	 * @param T
	 * @param methodName
	 *            name of method to execute
	 * @param methodArgument
	 *            need to match the methods in the webservice
	 * @return
	 */
	public <T> T invokeWebserviceService(Class<?> T, String methodName,
			Object... methodArgument) {
		T result = null;
		try {
			HttpServletRequest req = getRequest();
			String host = req.getServerName();
			String schema = "http";
			if ("https".equals(req.getScheme())) {
				schema = "https";
				// Need to overide HostnameVerifier otherwise it throws a
				// exception when we are using selfsigned certificates
				HostnameVerifier hv = new HostnameVerifier() {
					public boolean verify(String urlHostName, SSLSession session) {
						return true;
					}
				};
				HttpsURLConnection.setDefaultHostnameVerifier(hv);
			}
 
			String wsdlURL = schema + "://" + host
					+ "/webservices/RiskBean"
					+ schema.toUpperCase() + "?wsdl";
			URL url = new URL(wsdlURL);
 
			String ns = "http://reporting.ws.com/";
			QName qname = new QName(ns, "RiskService"
					+ schema.toUpperCase());
			QName port = new QName(ns, "RiskBean"
					+ schema.toUpperCase() + "Port");
			QName operation = new QName(ns, methodName);
 
			ServiceFactory riskServiceFactory = ServiceFactory.newInstance();
			Service riskService = riskServiceFactory.createService(url, qname);
 
			Call call = riskService.createCall(port, operation);
			result = (T) call.invoke(methodArgument);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

Hopefully someone finds this helpful.

Leave a Comment

Your email address will not be published. Required fields are marked *