HTTPCLIENT-1086: additional constructors for UrlEncodedFormEntity that take iterable as input

git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@1136437 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Oleg Kalnichevski 2011-06-16 13:50:02 +00:00
parent 2d017dcc0e
commit 21e31ba027
2 changed files with 58 additions and 0 deletions

View File

@ -61,6 +61,24 @@ public class UrlEncodedFormEntity extends StringEntity {
(encoding != null ? encoding : HTTP.DEFAULT_CONTENT_CHARSET));
}
/**
* Constructs a new {@link UrlEncodedFormEntity} with the list
* of parameters in the specified encoding.
*
* @param parameters iterable collection of name/value pairs
* @param encoding encoding the name/value pairs be encoded with
* @throws UnsupportedEncodingException if the encoding isn't supported
*
* @since 4.2
*/
public UrlEncodedFormEntity (
final Iterable <? extends NameValuePair> parameters,
final String encoding) throws UnsupportedEncodingException {
super(URLEncodedUtils.format(parameters, encoding), encoding);
setContentType(URLEncodedUtils.CONTENT_TYPE + HTTP.CHARSET_PARAM +
(encoding != null ? encoding : HTTP.DEFAULT_CONTENT_CHARSET));
}
/**
* Constructs a new {@link UrlEncodedFormEntity} with the list
* of parameters with the default encoding of {@link HTTP#DEFAULT_CONTENT_CHARSET}
@ -73,4 +91,18 @@ public class UrlEncodedFormEntity extends StringEntity {
this(parameters, HTTP.DEFAULT_CONTENT_CHARSET);
}
/**
* Constructs a new {@link UrlEncodedFormEntity} with the list
* of parameters with the default encoding of {@link HTTP#DEFAULT_CONTENT_CHARSET}
*
* @param parameters iterable collection of name/value pairs
* @throws UnsupportedEncodingException if the default encoding isn't supported
*
* @since 4.2
*/
public UrlEncodedFormEntity (
final Iterable <? extends NameValuePair> parameters) throws UnsupportedEncodingException {
this(parameters, HTTP.DEFAULT_CONTENT_CHARSET);
}
}

View File

@ -199,6 +199,32 @@ public class URLEncodedUtils {
return result.toString();
}
/**
* Returns a String that is suitable for use as an <code>application/x-www-form-urlencoded</code>
* list of parameters in an HTTP PUT or HTTP POST.
*
* @param parameters The parameters to include.
* @param encoding The encoding to use.
*
* @since 4.2
*/
public static String format (
final Iterable<? extends NameValuePair> parameters,
final String encoding) {
final StringBuilder result = new StringBuilder();
for (final NameValuePair parameter : parameters) {
final String encodedName = encode(parameter.getName(), encoding);
final String value = parameter.getValue();
final String encodedValue = value != null ? encode(value, encoding) : "";
if (result.length() > 0)
result.append(PARAMETER_SEPARATOR);
result.append(encodedName);
result.append(NAME_VALUE_SEPARATOR);
result.append(encodedValue);
}
return result.toString();
}
private static String decode (final String content, final String encoding) {
try {
return URLDecoder.decode(content,