|
| 1 | +package javajs.http; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.OutputStream; |
| 5 | +import java.net.HttpURLConnection; |
| 6 | +import java.util.List; |
| 7 | + |
| 8 | +import javajs.http.SimpleHttpClient.Request.FormData; |
| 9 | + |
| 10 | +/** |
| 11 | + * A simple Java byte[] or String poster. |
| 12 | + * |
| 13 | + * A java client that implements multipart form submit over https implemented |
| 14 | + * with only jdk classes and no external dependencies. |
| 15 | + * |
| 16 | + * Not used in SwingJ. HTML5 does not allow setting content-type to |
| 17 | + * multipart/form-data. Instead, for JavaScript, we simply load up an array of |
| 18 | + * information and turn that into a FormData object in AjaxURLConnection. |
| 19 | + * |
| 20 | + * adapted from https://github.com/atulsm/https-multipart-purejava |
| 21 | + * |
| 22 | + * @author Bob Hanson |
| 23 | + * |
| 24 | + */ |
| 25 | +public class JavaHttpPoster { |
| 26 | + |
| 27 | + public static void post(HttpURLConnection conn, List<FormData> formData) throws IOException { |
| 28 | + String boundary = "---" + System.nanoTime() + "---"; |
| 29 | + conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); |
| 30 | + OutputStream os = conn.getOutputStream(); |
| 31 | + for (int i = 0; i < formData.size(); i++) { |
| 32 | + FormData data = formData.get(i); |
| 33 | + String name = data.getName(); |
| 34 | + Object value = data.getData(); |
| 35 | + String contentType = data.getContentType(); |
| 36 | + String fileName = data.getFileName(); |
| 37 | + append(os, "--" + boundary + "\r\n"); |
| 38 | + append(os, "Content-Disposition: form-data; name=\"" + name |
| 39 | + + (fileName == null ? "" : "\"; filename=\"" + fileName) + "\""); |
| 40 | + append(os, "\r\nContent-Type: "); |
| 41 | + append(os, contentType == null ? "application/octet-stream" : contentType); |
| 42 | + append(os, "\r\n\r\n"); |
| 43 | + append(os, value); |
| 44 | + append(os, "\r\n"); |
| 45 | + } |
| 46 | + append(os, "\r\n--" + boundary + "--\r\n"); |
| 47 | + os.flush(); |
| 48 | + |
| 49 | + } |
| 50 | + |
| 51 | + private static void append(OutputStream outputStream, Object val) throws IOException { |
| 52 | + if (val instanceof byte[]) { |
| 53 | + outputStream.write((byte[]) val); |
| 54 | + } else { |
| 55 | + outputStream.write(val.toString().getBytes()); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | +} |
0 commit comments