Getting data from a web service from a java application
Hi Experts.
I have been working in Java for a while now, but have never had to interact with a web service. I have built a program using the JSDK that needs to query a web service. I'm not sure where to start with this :confused: .
All i know is that I will be getting a URL that i must call and i must pass a number to this URL. I must then expect a XML document back.
I'm maybe looking for someone to tell me more or less what to expect or do :SICK: .
1) How do I link to the web service from a Java application? Do i simply create a socket connection to the URL on port 80. Example http://www.dummywebservice.com?number=1000.
2) Is there any other information (http header) that must be sent?
3) Is the XML returned via the socket connection? Do i just read this in as if i was reading in a object over a socket?
4) Are there any existing simple web services that follow i can use to query try and get this working? What are they and how do I query them?
I'm really new to this and it kind of needs to be done quick. Any help would be really good. If possible demo code will help a lot.
Please help me, Thanks.
(MC3)RaVeN :)
I've posted this one many times....
..but noone has complained yet, so I guess it's working :)
Code:
import java.net.*;
import java.io.*;
/**
* Gets the contents of an url as a stringBuffer.
Usage example:
try {
URL url=new URL("http://www.whatever.com/servlets/xyz?number=1000");
SiteConn aConnection=new SiteConn(url);
StringBuffer sb=aConnection.getContens();
System.out.println(sb.toString());
} catch (MalFormedURLException mfe) {
System.err.println(mfe.getMessage());
}
*
*/
class SiteConn {
URL url = null;
public SiteConn(URL url) {
this.url = url;
}
public StringBuffer getContents() throws Exception {
StringBuffer buffer;
String line;
int responseCode;
HttpURLConnection connection;
InputStream input;
BufferedReader dataInput;
connection = (HttpURLConnection) url.openConnection();
responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new Exception("HTTP response code: " +
String.valueOf(responseCode));
}
try {
buffer = new StringBuffer();
input = connection.getInputStream();
dataInput = new BufferedReader(new InputStreamReader(input));
while ( (line = dataInput.readLine()) != null) {
buffer.append(line);
buffer.append("\r\n");
}
input.close();
}
catch (Exception ex) {
ex.printStackTrace(System.err);
return null;
}
return buffer;
}
}