Skip to content

Commit 30bbb6e

Browse files
Update HttpRequest library to allow for nested params
See kevinsawicki/http-request#147
1 parent f467402 commit 30bbb6e

File tree

1 file changed

+48
-6
lines changed

1 file changed

+48
-6
lines changed

src/android/com/github/kevinsawicki/http/HttpRequest.java

Lines changed: 48 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3356,6 +3356,25 @@ public HttpRequest form(final Object name, final Object value)
33563356
*/
33573357
public HttpRequest form(final Object name, final Object value, String charset)
33583358
throws HttpRequestException {
3359+
List<Object> names = new ArrayList<Object>();
3360+
names.add(name);
3361+
return form(names, value, charset);
3362+
}
3363+
3364+
/**
3365+
* Write the name/value pair as form data to the request body
3366+
* <p>
3367+
* The values specified will be URL-encoded and sent with the
3368+
* 'application/x-www-form-urlencoded' content-type
3369+
*
3370+
* @param names Name of param, as a list of ancestors
3371+
* @param value
3372+
* @param charset
3373+
* @return this request
3374+
* @throws HttpRequestException
3375+
*/
3376+
public HttpRequest form(final List<Object> names, final Object value, String charset)
3377+
throws HttpRequestException {
33593378
final boolean first = !form;
33603379
if (first) {
33613380
contentType(CONTENT_TYPE_FORM, charset);
@@ -3364,12 +3383,35 @@ public HttpRequest form(final Object name, final Object value, String charset)
33643383
charset = getValidCharset(charset);
33653384
try {
33663385
openOutput();
3367-
if (!first)
3368-
output.write('&');
3369-
output.write(URLEncoder.encode(name.toString(), charset));
3370-
output.write('=');
3371-
if (value != null)
3372-
output.write(URLEncoder.encode(value.toString(), charset));
3386+
if (value instanceof List<?>) {
3387+
names.add("");
3388+
for (Object item : (List<Object>)value)
3389+
form(names, item, charset);
3390+
names.remove(names.size() - 1);
3391+
} else if (value instanceof Map<?, ?>) {
3392+
for (Entry<Object, Object> entry : ((Map<Object, Object>)value).entrySet()) {
3393+
names.add(entry.getKey());
3394+
form(names, entry.getValue(), charset);
3395+
names.remove(names.size() - 1);
3396+
}
3397+
} else {
3398+
if (!first)
3399+
output.write('&');
3400+
3401+
boolean firstName = true;
3402+
for (Object name : names) {
3403+
if (!firstName)
3404+
output.write('[');
3405+
output.write(URLEncoder.encode(name.toString(), charset));
3406+
if (!firstName)
3407+
output.write(']');
3408+
firstName = false;
3409+
}
3410+
3411+
output.write('=');
3412+
if (value != null)
3413+
output.write(URLEncoder.encode(value.toString(), charset));
3414+
}
33733415
} catch (IOException e) {
33743416
throw new HttpRequestException(e);
33753417
}

0 commit comments

Comments
 (0)