Code formating and whitespace cleanup
[jpim.git] / src / de / j32 / httplib / HttpPOSTRequest.java
1 package de.j32.httplib;
2
3 import java.io.IOException;
4 import java.io.OutputStream;
5 import java.io.OutputStreamWriter;
6 import java.io.Writer;
7
8 public class HttpPOSTRequest extends HttpRequest
9 {
10     boolean multipart_ = false;
11     static final String separator_ = "----MultiPartFormData--MultiPartFormData--MultiPartFormData----";
12
13     public HttpPOSTRequest(String url)
14     {
15         super(url, "POST");
16         setContentType("application/x-www-form-urlencoded; charset=utf-8");
17     }
18
19     public HttpPOSTRequest setMultipart(boolean flag)
20     {
21         multipart_ = flag;
22         if (multipart_) {
23             setContentType("multipart/form-data; boundary=" + separator_);
24             try {
25                 OutputStream body = body();
26                 body.write("--".getBytes());
27                 body.write(separator_.getBytes());
28                 body.write("\r\n".getBytes());
29             }
30             catch (IOException e) {
31                 throw new AssertionError(
32                         "ByteArrayOutputStream throwing IOExcpetion");
33             }
34         }
35         return this;
36     }
37
38     @Override
39     public HttpRequest addParameter(String name, byte[] value, String encoding)
40     {
41         try {
42             if (multipart_) {
43                 OutputStream body = body();
44                 body.write("Content-Disposition: form-data; name=\"".getBytes());
45                 body.write(name.getBytes());
46                 body.write("\"\r\n".getBytes());
47                 body.write("Content-Type: text/plain; charset=".getBytes());
48                 body.write(encoding.getBytes());
49                 body.write("\r\n".getBytes());
50                 body.write(("Content-Length: " + value.length).getBytes());
51                 body.write("\r\n\r\n".getBytes());
52                 body.write(value);
53                 body.write("\r\n--".getBytes());
54                 body.write(separator_.getBytes());
55                 body.write("\r\n".getBytes());
56             }
57             else {
58                 // Encoding not really relevant here since url-encoding is plain
59                 // ASCII
60                 Writer writer = new OutputStreamWriter(body(), "ascii");
61                 appendParameter(writer, body().size() == 0, name, value);
62                 writer.flush();
63             }
64         }
65         catch (IOException e) {
66             throw new AssertionError(
67                     "ByteArrayOutputStream throwing IOExcpetion");
68         }
69         return this;
70     }
71 }