Archive

Archive for January, 2016

Call an ASMX webservice from Java

This is by no means the most elegant way of doing this, and I’d actively encourage using better code, but this works, and you’re welcome to copy it.

It uses the Norwegian asmx car lookup service here; http://no.registreringsnummerapi.com/developers.html

import java.net.*;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;

public class HelloWorld {

public static void main(String[] args) {
try{

String host = “www.regcheck.org.uk”;
Socket socket = new Socket(host, 80);
// change yourusernamehere
String request = “GET http://www.regcheck.org.uk/api/reg.asmx/CheckNorway?RegistrationNumber=BS23162&username=yourusernamehere HTTP/1.0\r\n\r\n”;
OutputStream os = socket.getOutputStream();
os.write(request.getBytes());
os.flush();

InputStream in = socket.getInputStream();
StringBuilder sb=new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String read;

while((read=br.readLine()) != null) {
//System.out.println(read);
sb.append(read);
}

br.close();
String strXml = sb.toString();
int intStart = strXml.indexOf(“<?xml”);
strXml = strXml.substring(intStart);
//System.out.print(strXml);
socket.close();

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
ByteArrayInputStream input = new ByteArrayInputStream(strXml.getBytes(“UTF-8”));
Document doc = builder.parse(input);
NodeList nList = doc.getElementsByTagName(“Description”);
Node nNode = nList.item(0);
System.out.print(nNode.getTextContent());
}
catch(Exception ex)
{
System.out.print(“Error”);
}

}

}

Categories: Uncategorized