Rename pimstuff -> jpim and move to Maven
[jpim.git] / src / main / java / de / j32 / httplib / HttpPOSTRequest.java
diff --git a/src/main/java/de/j32/httplib/HttpPOSTRequest.java b/src/main/java/de/j32/httplib/HttpPOSTRequest.java
new file mode 100644 (file)
index 0000000..d9ae78e
--- /dev/null
@@ -0,0 +1,71 @@
+package de.j32.httplib;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+
+public class HttpPOSTRequest extends HttpRequest
+{
+    boolean multipart_ = false;
+    static final String separator_ = "----MultiPartFormData--MultiPartFormData--MultiPartFormData----";
+
+    public HttpPOSTRequest(String url)
+    {
+        super(url, "POST");
+        setContentType("application/x-www-form-urlencoded; charset=utf-8");
+    }
+
+    public HttpPOSTRequest setMultipart(boolean flag)
+    {
+        multipart_ = flag;
+        if (multipart_) {
+            setContentType("multipart/form-data; boundary=" + separator_);
+            try {
+                OutputStream body = body();
+                body.write("--".getBytes());
+                body.write(separator_.getBytes());
+                body.write("\r\n".getBytes());
+            }
+            catch (IOException e) {
+                throw new AssertionError(
+                        "ByteArrayOutputStream throwing IOExcpetion");
+            }
+        }
+        return this;
+    }
+
+    @Override
+    public HttpRequest addParameter(String name, byte[] value, String encoding)
+    {
+        try {
+            if (multipart_) {
+                OutputStream body = body();
+                body.write("Content-Disposition: form-data; name=\"".getBytes());
+                body.write(name.getBytes());
+                body.write("\"\r\n".getBytes());
+                body.write("Content-Type: text/plain; charset=".getBytes());
+                body.write(encoding.getBytes());
+                body.write("\r\n".getBytes());
+                body.write(("Content-Length: " + value.length).getBytes());
+                body.write("\r\n\r\n".getBytes());
+                body.write(value);
+                body.write("\r\n--".getBytes());
+                body.write(separator_.getBytes());
+                body.write("\r\n".getBytes());
+            }
+            else {
+                // Encoding not really relevant here since url-encoding is plain
+                // ASCII
+                Writer writer = new OutputStreamWriter(body(), "ascii");
+                appendParameter(writer, body().size() == 0, name, value);
+                writer.flush();
+            }
+        }
+        catch (IOException e) {
+            throw new AssertionError(
+                    "ByteArrayOutputStream throwing IOExcpetion");
+        }
+        return this;
+    }
+}