1

I am trying to create a simple REST web-server. The actual URL looks like this

http://localhost:8080/Server/files/file?id=34?firstname=alex?lastname=ozouf?age=33?firstname=kevin?lastname=gerfild?age=27

The first ID is the ID of the requested file,the number of person in the parameter is not know in advance. I want to group this person in a collection/map.

It's not mandatory for the URL to be structured in this way. I could also use this URL if it could make it easier

http://localhost:8080/Server/files/file?id=34?firstname1=alex?lastname1=ozouf?age1=33?firstname2=kevin?lastname2=gerfild?age2=27

I tried to adapt these codes but as a newbie it I got really confused.

This is my code

System.out.println(query);
final Map<String, List<String>> query_pairs = new LinkedHashMap<String, List<String>>();
final String[] pairs = query.split("&");
for (String pair : pairs) {
    final int idx = pair.indexOf("=");
    final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
    if (!query_pairs.containsKey(key)) {
        query_pairs.put(key, new LinkedList<String>());
    }
    final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
    query_pairs.get(key).add(value);
    System.out.println(query_pairs);

And this is the output I got

{id=[23?firstname1=alex]}
{id=[23?firstname1=alex], lastname1=[ozouf]}
{id=[23?firstname1=alex], lastname1=[ozouf], age1=[23?firstname=kevin]}
{id=[23?firstname1=alex], lastname1=[ozouf], age1=[23?firstname=kevin], lastname=[gefild?age=22]}
Community
  • 1
  • 1
user3235881
  • 487
  • 2
  • 9
  • 24
  • 3
    you have a lot of ? in your URL. Note that only the beginning of the query string has an ? - all other parameters are separated by & like ?id=34&firstname=Jan&age=41 – Jan Apr 26 '16 at 15:02
  • 2
    and... are you trying to code your client here (how to call that URL) or your server? In the latter case you could simply iterate request.getParameterNames() on your HttpServletRequest maybe? – Jan Apr 26 '16 at 15:04

1 Answers1

0

You have the wrong query string "&" is the parameter separator.

http://localhost:8080/Server/files/file?id=34&firstname=alex&lastname=ozouf&age=33&firstname=kevin&lastname=gerfild&age=27

Also I see that you are trying to have two records at the same time in the URL that's impossible to have to objects records in the query string. For this use the POST method and it body.

Sayakiss
  • 6,878
  • 8
  • 61
  • 107
victor sosa
  • 899
  • 13
  • 27