Skip to content
Browse files

Merge pull request #392 from hongrich/master

RequestBuilder: Support Iterable / Map for Field
  • Loading branch information...
2 parents 810bb53 + 5a1486a commit a942fcff82cd9b44490446a6fcdf3a00374c1186 @JakeWharton JakeWharton committed
View
17 retrofit/src/main/java/retrofit/RequestBuilder.java
@@ -241,7 +241,22 @@ void setArguments(Object[] args) {
break;
case FIELD:
if (value != null) { // Skip null values.
- formBody.addField(name, value.toString());
+ if (value instanceof Iterable) {
+ for (Object v : (Iterable<?>) value) {
+ if (v != null) { // Skip null values.
+ formBody.addField(name, v.toString());
+ }
+ }
+ } else if (value instanceof Map) {
+ for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
+ Object entryValue = entry.getValue();
+ if (entryValue != null) { // Skip null values.
+ formBody.addField(entry.getKey().toString(), entryValue.toString());
+ }
+ }
+ } else {
+ formBody.addField(name, value.toString());
+ }
}
break;
case PART:
View
46 retrofit/src/test/java/retrofit/RequestBuilderTest.java
@@ -499,6 +499,38 @@
assertTypedBytes(request.getBody(), "foo=bar&kit=kat");
}
+ @Test public void formEncodedFieldList() throws Exception {
+ List<Object> values = new ArrayList<Object>(Arrays.asList("foo", "bar", null, 3));
+
+ Request request = new Helper() //
+ .setMethod("POST") //
+ .setHasBody() //
+ .setUrl("http://example.com") //
+ .setPath("/foo") //
+ .setFormEncoded() //
+ .addFieldList("foo", values) //
+ .addField("kit", "kat") //
+ .build();
+ assertTypedBytes(request.getBody(), "foo=foo&foo=bar&foo=3&kit=kat");
+ }
+
+ @Test public void formEncodedFieldMap() throws Exception {
+ Map<String, Object> params = new LinkedHashMap<String, Object>();
+ params.put("kit", "kat");
+ params.put("foo", null);
+ params.put("ping", "pong");
+
+ Request request = new Helper() //
+ .setMethod("POST") //
+ .setHasBody() //
+ .setUrl("http://example.com") //
+ .setPath("/foo") //
+ .setFormEncoded() //
+ .addFieldMap("options", params) //
+ .build();
+ assertTypedBytes(request.getBody(), "kit=kat&ping=pong");
+ }
+
@Test public void simpleHeaders() throws Exception {
Request request = new Helper() //
.setMethod("GET") //
@@ -697,6 +729,20 @@ Helper addField(String name, String value) {
return this;
}
+ Helper addFieldList(String name, List<Object> values) {
+ paramNames.add(name);
+ paramUsages.add(FIELD);
+ args.add(values);
+ return this;
+ }
+
+ Helper addFieldMap(String name, Map<String, Object> values) {
+ paramNames.add(name);
+ paramUsages.add(FIELD);
+ args.add(values);
+ return this;
+ }
+
Helper addPart(String name, Object value) {
paramNames.add(name);
paramUsages.add(PART);

0 comments on commit a942fcf

Please sign in to comment.
Something went wrong with that request. Please try again.