6

I use this code to get values from an HTTP request:

@PostMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, value = "/v1/notification")
  public ResponseEntity<String> handleNotifications(@RequestBody MultiValueMap<String, Object> keyValuePairs) {

    LOGGER.debug("handleFormMessage");
    LOGGER.debug("keyValuePairs: {}", keyValuePairs);

    String unique_id = String.valueOf(keyValuePairs.get("unique_id"));

    System.out.println("!!!!!!!!!!!!!! ! unique_id " + unique_id);
}

But I get this value: !!!!!!!!!!!!!! ! unique_id [24q376c3ts2kh3o3220rry322dfe2k7y].

Is there a way to remove [] from the String without the classical String result = str.substring(0, index) + str.substring(index+1);?

Is there a way to get the values?

I use this to post the values:

enter image description here

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
Peter Penzov
  • 1,126
  • 134
  • 430
  • 808

2 Answers2

5

If you always provide only one value for unique_id, you can, instead of get, use getFirst which

Returns the first value for the given key

Your code would go like this:

String unique_id = String.valueOf(keyValuePairs.getFirst("unique_id"));

Remember, this method actually returns the first value for the specified key, or null if none is found.


In case you send more than one value you need to treat them as a Collection. For example:

Collection<String> unique_ids = keyValuePairs.get("unique_id");

After that you can do with all the ids as you wish, for example, print them:

unique_ids.stream().forEach(System.out:println);
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
2

MultivaluedMap is an interface inheriting Map, and how you can see the object you get is a list

public interface MultivaluedMap<K,V> extends Map<K,List<V>>

Then you can do this and get the first element of the list:

String unique_id = String.valueOf(keyValuePairs.getFirst("unique_id"));
Francesc Recio
  • 2,187
  • 2
  • 13
  • 26