A helper class. Copy into a file named PostHelper.java.
/* * @file * A class to help making POST requests */ package nl.wur.closedquestionappletdemo; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.SwingWorker; /** * A class to help making POST requests to a webserver. * The HTTP POST is done in a background thread, after the post is finished all * registered PostListeners are notified. * Post variables can be added with the addVar method. */ public class PostHelper { /** * The interface that must be implemented by classes that want to be * informed when a post is completed. */ public interface PostListener { /** * Called when the post is completed. */ public void postDone(); } /** * The encoding to use for posting. */ private String encoding = "UTF-8"; /** * The URL to post to. */ private URL postUrl; /** * The variables to post. */ private Map<String, String> postVars = new HashMap<String, String>(); /** * The response received from the server. */ private StringBuilder responseData = new StringBuilder(); /** * The headers received from the server. */ private Map<String, List<String>> responseHeaderFields = null; /** * Objects that want to be informed when the POST is completed. */ private List<PostListener> listeners = new ArrayList<PostListener>(); /** * A flag to indicate posting is in progress. */ private boolean posting = false; /** * The worker doing the loading work. */ private SwingWorker worker; /** * Create a new PostHelper that will post to the given URL. * * @param postUrl The url to post to. */ public PostHelper(URL postUrl) { this.postUrl = postUrl; } /** * Add a variable to the POST. The name and value will be URLEncoded before * sending. * * @param name The variable name. * @param value The variable content. */ public void addVar(String name, String value) { postVars.put(name, value); } /** * Clear all post vars. */ public void clearVars() { postVars.clear(); } /** * Do the actual post. */ public synchronized void doPost() { if (!posting) { posting = true; worker = new SwingWorker<Integer, Void>() { @Override protected Integer doInBackground() throws Exception { int statusCode = -1; try { StringBuilder postData = new StringBuilder(); for (Entry<String, String> entry : postVars.entrySet()) { postData.append(URLEncoder.encode(entry.getKey(), encoding)); postData.append("="); postData.append(URLEncoder.encode(entry.getValue(), encoding)); postData.append("&"); } Logger.getLogger(getClass().getName()).log(Level.FINER, "Posting to: {0}", postUrl); HttpURLConnection urlconnection = (HttpURLConnection) postUrl.openConnection(); urlconnection.setRequestMethod("POST"); urlconnection.setDoInput(true); urlconnection.setDoOutput(true); urlconnection.setUseCaches(false); urlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Send POST output. DataOutputStream printout = new DataOutputStream(urlconnection.getOutputStream()); printout.writeBytes(postData.toString()); printout.flush(); printout.close(); // Get response data. BufferedReader input = new BufferedReader(new InputStreamReader(urlconnection.getInputStream())); responseData = new StringBuilder(); String str; try { while (null != ((str = input.readLine()))) { responseData.append(str); } } catch (EOFException e) { Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Document end reached prematurely!"); } input.close(); statusCode = urlconnection.getResponseCode(); responseHeaderFields = urlconnection.getHeaderFields(); } catch (IOException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); } catch (ClassCastException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Can not post, not a HTTP(s) url", ex); } return statusCode; } @Override protected void done() { super.done(); posting = false; notifyDone(); } }; worker.execute(); } } /** * Get the returned page. * * @return The data returned by the server. */ public String getResponseData() { return responseData.toString(); } /** * Get the response headers. * * @return A map containing the response headers. */ public Map<String, List<String>> getResponseHeaderFields() { return responseHeaderFields; } /** * Add a PostListener to this PostHelper. * @param l The listener to add. */ public void addPostListener(PostListener l) { listeners.add(l); } /** * Remove a PostListener from this PostHelper. * @param l The listener to remove. */ public void removePostListener(PostListener l) { listeners.remove(l); } /** * Notify all listeners that posting is done. */ private void notifyDone() { PostListener[] list = new PostListener[listeners.size()]; list = listeners.toArray(list); for (PostListener l : list) { l.postDone(); } } }