From 20fd2a0bd7c2bcbd753bd91530daabc61e9c0a98 Mon Sep 17 00:00:00 2001 From: ray Date: Fri, 26 Sep 2003 02:36:41 +0000 Subject: [PATCH] Utility class to safely do a http POST request. git-svn-id: https://samskivert.googlecode.com/svn/trunk@1233 6335cc39-0255-0410-8fd6-9bcaacd3b74c --- .../java/com/samskivert/net/HttpPostUtil.java | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 projects/samskivert/src/java/com/samskivert/net/HttpPostUtil.java diff --git a/projects/samskivert/src/java/com/samskivert/net/HttpPostUtil.java b/projects/samskivert/src/java/com/samskivert/net/HttpPostUtil.java new file mode 100644 index 00000000..8b157327 --- /dev/null +++ b/projects/samskivert/src/java/com/samskivert/net/HttpPostUtil.java @@ -0,0 +1,81 @@ +// +// $Id: HttpPostUtil.java,v 1.1 2003/09/26 02:36:41 ray Exp $ + +package com.samskivert.net; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.InputStreamReader; +import java.io.IOException; + +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; + +import com.samskivert.util.ServiceWaiter; + +/** + * Contains utility methods for doing a form post. + */ +public class HttpPostUtil +{ + /** + * Return the results of a form post. Note that the http request takes + * place on another thread, but this thread blocks until the results + * are returned or it times out. + * + * @param url from which to make the request. + * @param submission the entire submission eg "foo=bar&baz=boo&futz=foo". + * @param timeout time to wait for the response, in seconds, or -1 + * for forever. + */ + public static String httpPost (final URL url, final String submission, + int timeout) + throws IOException, ServiceWaiter.TimeoutException + { + final ServiceWaiter waiter = new ServiceWaiter( + (timeout < 0) ? ServiceWaiter.NO_TIMEOUT : timeout); + Thread tt = new Thread() { + public void run () { + try { + HttpURLConnection conn = + (HttpURLConnection) url.openConnection(); + conn.setDoInput(true); + conn.setDoOutput(true); + conn.setUseCaches(false); + conn.setRequestProperty( + "Content-Type", "application/x-www-form-urlencoded"); + + DataOutputStream out = new DataOutputStream( + conn.getOutputStream()); + out.writeBytes(submission); + out.flush(); + out.close(); + + BufferedReader reader = new BufferedReader( + new InputStreamReader(conn.getInputStream())); + + StringBuffer buf = new StringBuffer(); + for (String s; null != (s = reader.readLine()); ) { + buf.append(s); + } + reader.close(); + + waiter.postSuccess(buf.toString()); // yay + + } catch (IOException e) { + waiter.postFailure(e); // boo + } + } + }; + + tt.start(); + + if (waiter.waitForResponse()) { + return (String) waiter.getArgument(); + + } else { + throw (IOException) waiter.getArgument(); + } + } +}