提交 0dbe1814 编写于 作者: E Eric Butler

Multipart request improvements.

* Added fileName() to TypedOutput so non-File parts can be named.
* Support Content-Length in multipart requests.
* Serialize parts to byte[]s so length is available.
上级 76350e15
...@@ -58,6 +58,10 @@ public class GsonConverter implements Converter { ...@@ -58,6 +58,10 @@ public class GsonConverter implements Converter {
this.jsonBytes = jsonBytes; this.jsonBytes = jsonBytes;
} }
@Override public String fileName() {
return null;
}
@Override public String mimeType() { @Override public String mimeType() {
return "application/json; charset=UTF-8"; return "application/json; charset=UTF-8";
} }
......
// Copyright 2013 Square, Inc. // Copyright 2013 Square, Inc.
package retrofit.http; package retrofit.http;
import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.LinkedHashMap; import java.util.ArrayList;
import java.util.Map; import java.util.List;
import java.util.UUID; import java.util.UUID;
import retrofit.http.mime.TypedFile;
import retrofit.http.mime.TypedOutput; import retrofit.http.mime.TypedOutput;
final class MultipartTypedOutput implements TypedOutput { final class MultipartTypedOutput implements TypedOutput {
final Map<String, TypedOutput> parts = new LinkedHashMap<String, TypedOutput>(); final List<byte[]> parts = new ArrayList<byte[]>();
private final byte[] footer;
private final String boundary; private final String boundary;
private long length;
MultipartTypedOutput() { MultipartTypedOutput() {
boundary = UUID.randomUUID().toString(); boundary = UUID.randomUUID().toString();
footer = buildBoundary(boundary, false, true);
length = footer.length;
} }
void addPart(String name, TypedOutput body) { void addPart(String name, TypedOutput body) {
...@@ -24,7 +28,14 @@ final class MultipartTypedOutput implements TypedOutput { ...@@ -24,7 +28,14 @@ final class MultipartTypedOutput implements TypedOutput {
if (body == null) { if (body == null) {
throw new NullPointerException("Part body must not be null."); throw new NullPointerException("Part body must not be null.");
} }
parts.put(name, body);
byte[] part = buildPart(name, body, parts.isEmpty());
parts.add(part);
length += part.length;
}
@Override public String fileName() {
return null;
} }
@Override public String mimeType() { @Override public String mimeType() {
...@@ -32,52 +43,70 @@ final class MultipartTypedOutput implements TypedOutput { ...@@ -32,52 +43,70 @@ final class MultipartTypedOutput implements TypedOutput {
} }
@Override public long length() { @Override public long length() {
return -1; return length;
} }
@Override public void writeTo(OutputStream out) throws IOException { @Override public void writeTo(OutputStream out) throws IOException {
boolean first = true; for (byte[] part : parts) {
for (Map.Entry<String, TypedOutput> part : parts.entrySet()) { out.write(part);
writeBoundary(out, boundary, first, false);
writePart(out, part);
first = false;
} }
writeBoundary(out, boundary, false, true); out.write(footer);
} }
private static void writeBoundary(OutputStream out, String boundary, boolean first, boolean last) private byte[] buildPart(String name, TypedOutput body, boolean first) {
throws IOException { ByteArrayOutputStream out = null;
StringBuilder sb = new StringBuilder(); try {
if (!first) { out = new ByteArrayOutputStream();
sb.append("\r\n"); out.write(buildBoundary(boundary, first, false));
out.write(buildHeader(name, body));
body.writeTo(out);
return out.toByteArray();
} catch (IOException ex) {
throw new RuntimeException("Unable to write multipart request.", ex);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException ignored) {
}
}
} }
sb.append("--"); }
sb.append(boundary);
if (last) { private static byte[] buildBoundary(String boundary, boolean first, boolean last) {
try {
StringBuilder sb = new StringBuilder();
if (!first) {
sb.append("\r\n");
}
sb.append("--"); sb.append("--");
} else { sb.append(boundary);
sb.append("\r\n"); if (last) {
sb.append("--");
} else {
sb.append("\r\n");
}
return sb.toString().getBytes("UTF-8");
} catch (IOException ex) {
throw new RuntimeException("Unable to write multipart boundary", ex);
} }
out.write(sb.toString().getBytes("UTF-8"));
} }
private static void writePart(OutputStream out, Map.Entry<String, TypedOutput> part) private byte[] buildHeader(String name, TypedOutput value) {
throws IOException { try {
String name = part.getKey(); StringBuilder headers = new StringBuilder();
TypedOutput value = part.getValue(); headers.append("Content-Disposition: form-data; name=\"");
headers.append(name);
StringBuilder headers = new StringBuilder(); if (value.fileName() != null) {
headers.append("Content-Disposition: form-data; name=\""); headers.append("\"; filename=\"");
headers.append(name); headers.append(value.fileName());
if (value instanceof TypedFile) { }
headers.append("\"; filename=\""); headers.append("\"\r\nContent-Type: ");
headers.append(((TypedFile) value).file().getName()); headers.append(value.mimeType());
headers.append("\r\nContent-Transfer-Encoding: binary\r\n\r\n");
return headers.toString().getBytes("UTF-8");
} catch (IOException ex) {
throw new RuntimeException("Unable to write multipart header", ex);
} }
headers.append("\"\r\nContent-Type: ");
headers.append(value.mimeType());
headers.append("\r\nContent-Transfer-Encoding: binary\r\n\r\n");
out.write(headers.toString().getBytes("UTF-8"));
value.writeTo(out);
} }
} }
...@@ -36,6 +36,10 @@ public class TypedByteArray implements TypedInput, TypedOutput { ...@@ -36,6 +36,10 @@ public class TypedByteArray implements TypedInput, TypedOutput {
return bytes; return bytes;
} }
@Override public String fileName() {
return null;
}
@Override public String mimeType() { @Override public String mimeType() {
return mimeType; return mimeType;
} }
...@@ -69,4 +73,4 @@ public class TypedByteArray implements TypedInput, TypedOutput { ...@@ -69,4 +73,4 @@ public class TypedByteArray implements TypedInput, TypedOutput {
result = 31 * result + Arrays.hashCode(bytes); result = 31 * result + Arrays.hashCode(bytes);
return result; return result;
} }
} }
\ No newline at end of file
...@@ -47,6 +47,10 @@ public class TypedFile implements TypedInput, TypedOutput { ...@@ -47,6 +47,10 @@ public class TypedFile implements TypedInput, TypedOutput {
return file.length(); return file.length();
} }
@Override public String fileName() {
return file.getName();
}
@Override public InputStream in() throws IOException { @Override public InputStream in() throws IOException {
return new FileInputStream(file); return new FileInputStream(file);
} }
......
...@@ -10,6 +10,10 @@ import java.io.OutputStream; ...@@ -10,6 +10,10 @@ import java.io.OutputStream;
* @author Bob Lee (bob@squareup.com) * @author Bob Lee (bob@squareup.com)
*/ */
public interface TypedOutput { public interface TypedOutput {
/** Original filename.
*
* Used only for multipart requests, may be null. */
String fileName();
/** Returns the mime type. */ /** Returns the mime type. */
String mimeType(); String mimeType();
......
...@@ -224,15 +224,13 @@ public class RequestBuilderTest { ...@@ -224,15 +224,13 @@ public class RequestBuilderTest {
MultipartTypedOutput body = (MultipartTypedOutput) request.getBody(); MultipartTypedOutput body = (MultipartTypedOutput) request.getBody();
assertThat(body.parts).hasSize(2); assertThat(body.parts).hasSize(2);
Iterator<Map.Entry<String, TypedOutput>> iterator = body.parts.entrySet().iterator(); Iterator<byte[]> iterator = body.parts.iterator();
Map.Entry<String, TypedOutput> one = iterator.next(); String one = new String(iterator.next(), "UTF-8");
assertThat(one.getKey()).isEqualTo("ping"); assertThat(one).contains("ping").contains("pong");
assertTypedBytes(one.getValue(), "pong");
Map.Entry<String, TypedOutput> two = iterator.next(); String two = new String(iterator.next(), "UTF-8");
assertThat(two.getKey()).isEqualTo("kit"); assertThat(two).contains("kit").contains("kat");
assertTypedBytes(two.getValue(), "kat");
} }
@Test public void simpleHeaders() throws Exception { @Test public void simpleHeaders() throws Exception {
......
...@@ -64,11 +64,14 @@ public class UrlConnectionClientTest { ...@@ -64,11 +64,14 @@ public class UrlConnectionClientTest {
DummyHttpUrlConnection connection = (DummyHttpUrlConnection) client.openConnection(request); DummyHttpUrlConnection connection = (DummyHttpUrlConnection) client.openConnection(request);
client.prepareRequest(connection, request); client.prepareRequest(connection, request);
byte[] output = connection.getOutputStream().toByteArray();
assertThat(connection.getRequestMethod()).isEqualTo("POST"); assertThat(connection.getRequestMethod()).isEqualTo("POST");
assertThat(connection.getURL().toString()).isEqualTo(HOST + "/that/"); assertThat(connection.getURL().toString()).isEqualTo(HOST + "/that/");
assertThat(connection.getRequestProperties()).hasSize(1); assertThat(connection.getRequestProperties()).hasSize(2);
assertThat(connection.getRequestProperty("Content-Type")).startsWith("multipart/form-data;"); assertThat(connection.getRequestProperty("Content-Type")).startsWith("multipart/form-data;");
assertThat(connection.getOutputStream().toByteArray().length).isGreaterThan(0); assertThat(connection.getRequestProperty("Content-Length")).isEqualTo(String.valueOf(output.length));
assertThat(output.length).isGreaterThan(0);
} }
@Test public void headers() throws Exception { @Test public void headers() throws Exception {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册