I need to send an array of key-value pairs via HttpURLConnection and here's the catch - there could be many pairs having the same key and/or the same value, like so:
{[key1,val1], [key1,val2], [key2,val2] ... }
I tried the following but the problem is that it does not accommodate for multiple pairs having the same key but different values:
Map<String, String> params) throws IOException {
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoInput(true); // true indicates the server returns response
StringBuffer requestParams = new StringBuffer();
if (params != null && params.size() > 0) {
httpConn.setDoOutput(true); // true indicates POST request
// creates the params string, encode them using URLEncoder
Iterator<String> paramIterator = params.keySet().iterator();
while (paramIterator.hasNext()) {
String key = paramIterator.next();
String value = params.get(key);
requestParams.append(URLEncoder.encode(key, "UTF-8"));
requestParams.append("=").append(
URLEncoder.encode(value, "UTF-8"));
requestParams.append("&");
}
// sends POST data
OutputStreamWriter writer = new OutputStreamWriter(
httpConn.getOutputStream());
writer.write(requestParams.toString());
writer.flush();
}
Any suggestions on how this array of key-value pairs can be sent via POST?
NOTE: For reasons, I do not want to use anything from the org.apache.http package.
$_POST