--- /dev/null
+package de.j32.httplib;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLEncoder;
+
+public abstract class HttpRequest
+{
+ StringBuffer url_;
+ StringBuffer query_ = new StringBuffer();
+ String method_;
+ ByteArrayOutputStream body_ = new ByteArrayOutputStream();
+ String contentType_;
+
+ public HttpRequest(String url, String method)
+ {
+ url_ = new StringBuffer(url);
+ method_ = method;
+ }
+
+ protected StringBuffer query()
+ {
+ return query_;
+ }
+
+ protected ByteArrayOutputStream body()
+ {
+ return body_;
+ }
+
+ protected void setContentType(String c)
+ {
+ contentType_ = c;
+ }
+
+ protected static void appendParameter(Appendable buffer, boolean first,
+ String name, byte[] value)
+ {
+ try {
+ if (!first) buffer.append("&");
+ buffer.append(URLEncoder.encode(name, "utf-8"));
+ buffer.append("=");
+ // We really would need a URLEncoder for byte[] (pre-encoded or raw
+ // date)
+ buffer.append(URLEncoder
+ .encode(new String(value, "ascii"), "ascii"));
+ }
+ catch (UnsupportedEncodingException e) {
+ throw new AssertionError("Missing encoding");
+ }
+ catch (IOException e) {
+ throw new AssertionError("IOException on buffer-based Appendable");
+ }
+ }
+
+ public HttpResponse execute() throws MalformedURLException, IOException
+ {
+ if (query_.length() > 0) url_.append("?");
+ url_.append(query_);
+ HttpURLConnection connection = (HttpURLConnection) new URL(new String(
+ url_)).openConnection();
+ connection.setRequestMethod(method_);
+ if (contentType_ != null) {
+ connection.setRequestProperty("Content-Type", contentType_);
+ connection.setDoOutput(true);
+ connection.setFixedLengthStreamingMode(body_.size());
+ connection.getOutputStream().write(body_.toByteArray());
+ }
+ if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) throw new IOException(
+ "HTTP request failed: " + connection.getResponseCode() + " "
+ + connection.getResponseMessage());
+ return new HttpResponse(connection);
+ }
+
+ public HttpRequest addParameter(String name, String value)
+ throws UnsupportedEncodingException
+ {
+ return addParameter(name, value, "utf-8");
+ }
+
+ public HttpRequest addParameter(String name, String value, String encoding)
+ throws UnsupportedEncodingException
+ {
+ return addParameter(name, value.getBytes(encoding), encoding);
+ }
+
+ abstract public HttpRequest addParameter(String name, byte[] value,
+ String encoding);
+}