How to make a java xml post ?
XML is a great web standard that let you easily pack any kind of informations in a very easy understanding format, that can be easily passed between servers, validated and so on ( For more informations about XML and such u can read articles in our xml category.
Java, the well known OOP language developed by Sun Microsystems, is very very powerful when it comes to communications. We don’t speak here about the Internet oriented java part that is the beans, servlets stuffs. We are just using java as a desktop programming language.
As I mentioned before, when it comes to communications, anything i possible in JAVA. Be it sockets or datagrams, client or server program. All are easy to accomplish.
Those being said, you probably need to send a XML message to a server, via POST method, because that’s what this article intends to talk about. We don’t want to do here a fancy GUI for that. The purpose of this is only the communication part. The script proposed here will be a console based one. Let’s consider the snippet:
try { URL url = new URL(args[0]);String document = args[1];FileReader fr = new FileReader(document);char[] buffer = new char[1024*10];
int b_read = 0;
if ((b_read = fr.read(buffer)) != -1)
{
URLConnection urlc = url.openConnection();
urlc.setRequestProperty("Content-Type","text/xml");
urlc.setDoOutput(true);
urlc.setDoInput(true);
PrintWriter pw = new PrintWriter(urlc.getOutputStream());
pw.write(buffer, 0, b_read);
pw.close();
BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String inputLine;
while ((res_line = in.readLine()) != null)
System.out.println(res_line);
in.close();
}
}
catch (Exception e) {
//Threat the exceptions here
}
This piece of snippet read the XML from a file given as the second parameter into the command line and put it into the “buffer” object. Off course if you have the xml in an object in your code you can just put it into the buffer object or use your own object. Also the url of the server that post the xml to is given from the command line ( args[0] ).
First we send the buffer’s content by setting the connection object to accept input, taking the PrintWriter instance of the connection and writing the contents to it :
urlc.setDoInput(true);
urlc.setDoInput(true);PrintWriter pw = new PrintWriter(urlc.getOutputStream());pw.write(buffer, 0, b_read);
Next we read the response and print in to the console via an usual method using a BufferedReader object:
BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream()));String inputLine; while ((res_line = in.readLine()) != null) System.out.println(res_line);

RSS/XML