Home > Uncategorized > Call an ASMX webservice from Java

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”);
}

}

}

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: