JAVATM MASTER

Post Method

Back to Table of Contents

This method will work with any version of javaTM and will work in Applets as long as the server you post to is the same as the server that the Applet resides on. Of course that restriction does not apply for JSP, Servlets, and Applications which can also use this method.

import java.net.*;
import java.io.*;
import java.util.*;

	/**
	 * Post Method that does all the work for Posting
	 * to the Server. Posts a String to a URL Connection 
	 * on a server and returns the String that is read back.
	 * @param destURL the URL to post to.
	 * @param RawData contains the data to send as a String.
	 * @return the raw String returned from the server.
	 */
	public synchronized String post(URL destURL, String RawData){
		DataOutputStream outStream = null;
		DataInputStream inStream = null;
		String FeedS ="";
		if (destURL == null) throw new 
			NullPointerException("destURL is null.");
		try{
			URLConnection urlConn = destURL.openConnection();

			urlConn.setDoOutput(true);
			urlConn.setDoInput(true);
			urlConn.setUseCaches(false);

			urlConn.setRequestProperty("Content-type",
				"application/x-www-form-urlencoded");
			urlConn.setRequestProperty("Content-length",
				""+RawData.length());

			outStream = new DataOutputStream(
				urlConn.getOutputStream());
			outStream.writeBytes(RawData);
			outStream.flush();
			outStream.close();
			outStream = null;

			inStream = new DataInputStream(
				urlConn.getInputStream());
			int ch;
			StringBuffer Buf = new StringBuffer();
			while((ch = inStream.read()) >= 0){
				Buf.append((char)ch);
			}
			FeedS = Buf.toString();
			inStream.close();
			inStream = null;
		}
		catch(Exception ex){
			System.out.println("post err: "+ex.toString());
		}
		finally{
			try{
				if (inStream != null)
   					inStream.close();
			}
			catch(IOException ex){}
			try{
				if (outStream != null)
 					outStream.close();
			}
			catch(IOException ex){}
		}
		return FeedS;
	}

Essentially this method posts to a Server and retrieves info back which it returns as a String. The other way of sending data to a server is the Get method which has the data appended to the end of the URL after a question mark.

For example, if you want to send info to http://www.foobar.com/someserv.jsp you would do something like:

http://www.foobar.com/someserv.jsp?myvar=hi&myothervar=hello

Using the Get method may be convenient, but the amount of data you can send is limited, unlike for the Post method which has no limit. Also, somethings you would not want to append to the end of the URL for everyone to read, such as credit card info. For such info you should use the Post method.

As for credit card info, you may also want to encript your data before you send it across the web.

When sending name = value pairs across the web, you should URLEncode them with the method:
String java.net.URLEncoder.encode(String value) as such:

	public static String encodeData(String[] Names, String[] Values){
		StringBuffer buf = new StringBuffer();
		for (int i=0; i < Names.length && i < Values.length; i++){
			if (i > 0) buf.append("&");
			buf.append(URLEncoder.encode(Names[i])+
				"="+URLEncoder.encode(Values[i]));
		}
		return buf.toString();
	}
	
To decode the String you get back you could use this method:

	public static Properties decodeData(String FeedS){
		Properties PData = new Properties();
		StringTokenizer Splitter = new StringTokenizer(FeedS, "&", false);
		while(Splitter.hasMoreTokens()){
			String pair = Splitter.nextToken();
			int i = pair.indexOf("=");
			if (i > 0){
				PData.setProperty(
					URLDecoder.decode(pair.substring(0,i)),
					URLDecoder.decode(pair.substring(i+1)));
			}
		}
		return PData;
	}

Note that URLEncoder is present in all versions of java but URLDecoder is only availiable in jdk1.2 and later. So if you are using this in an Applet, you may want to consider making your own URLDecoder. It works the opposite to the URLEncoder, where encoded text has '+' charaters instead of spaces and all non alphanumeric characters are converted to their two digit ASCII Hex equivilent preceded by the percent ('%') char. Also, each name value pair is divided by an equal sign ('=') and the pairs are separated by a ampersand ('&').

*OracleTM and JavaTM are registered trademarks of Oracle and or its affiliates. Other names may be trademarks of their respective owners.*