Skip to content

Commit

Permalink
Update HttpRequest library to allow for nested params
Browse files Browse the repository at this point in the history
  • Loading branch information
entretechno-jeremiah committed Aug 8, 2018
1 parent f467402 commit 30bbb6e
Showing 1 changed file with 48 additions and 6 deletions.
54 changes: 48 additions & 6 deletions src/android/com/github/kevinsawicki/http/HttpRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -3356,6 +3356,25 @@ public HttpRequest form(final Object name, final Object value)
*/
public HttpRequest form(final Object name, final Object value, String charset)
throws HttpRequestException {
List<Object> names = new ArrayList<Object>();
names.add(name);
return form(names, value, charset);
}

/**
* Write the name/value pair as form data to the request body
* <p>
* The values specified will be URL-encoded and sent with the
* 'application/x-www-form-urlencoded' content-type
*
* @param names Name of param, as a list of ancestors
* @param value
* @param charset
* @return this request
* @throws HttpRequestException
*/
public HttpRequest form(final List<Object> names, final Object value, String charset)
throws HttpRequestException {
final boolean first = !form;
if (first) {
contentType(CONTENT_TYPE_FORM, charset);
Expand All @@ -3364,12 +3383,35 @@ public HttpRequest form(final Object name, final Object value, String charset)
charset = getValidCharset(charset);
try {
openOutput();
if (!first)
output.write('&');
output.write(URLEncoder.encode(name.toString(), charset));
output.write('=');
if (value != null)
output.write(URLEncoder.encode(value.toString(), charset));
if (value instanceof List<?>) {
names.add("");
for (Object item : (List<Object>)value)
form(names, item, charset);
names.remove(names.size() - 1);
} else if (value instanceof Map<?, ?>) {
for (Entry<Object, Object> entry : ((Map<Object, Object>)value).entrySet()) {
names.add(entry.getKey());
form(names, entry.getValue(), charset);
names.remove(names.size() - 1);
}
} else {
if (!first)
output.write('&');

boolean firstName = true;
for (Object name : names) {
if (!firstName)
output.write('[');
output.write(URLEncoder.encode(name.toString(), charset));
if (!firstName)
output.write(']');
firstName = false;
}

output.write('=');
if (value != null)
output.write(URLEncoder.encode(value.toString(), charset));
}
} catch (IOException e) {
throw new HttpRequestException(e);
}
Expand Down

0 comments on commit 30bbb6e

Please sign in to comment.