Java - Convert Object to URL Encoded Form

Do you need to convert a Java object to URL encoded form (application/x-www-form-urlencoded) string? This tutorial gives you example how to do so by creating a reusable utiity method that can be used for instances of different classes.

Sometimes you may need to convert an object to URL encoded form (application/x-www-form-urlencoded) before sending it as request body. Assuming your object only has fields with primitive type, it can be done easily. This example below only works if the class of the object only contains properties with primitive type.

Dependencies

We need ObjectMapper for getting object properties along with the value. For getting property type, we can uses beanutils.

  <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.9</version>
  </dependency>
  <dependency>
      <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
      <version>1.9.2</version>
  </dependency>

Code

Using ObjectMapper, we can get the list of properties and also the value of each property. Then, we check the type of the property using org.apache.commons.beanutils.PropertyUtils. If the property is String, we can directly get the value. If the property is not String but is primitive, we can cast the value to String. In this example, if the property is not primitive, it will be ignored. The value is URL-encoded using URLEncoder.encode method, append it after the key, so that the format is {key}={encoded value}, then join all properties with & symbol.

  package com.woolha.example.utils;
  
  import com.fasterxml.jackson.databind.ObjectMapper;
  
  import java.io.UnsupportedEncodingException;
  import java.lang.reflect.InvocationTargetException;
  import java.net.URLEncoder;
  import java.nio.charset.StandardCharsets;
  import java.util.Map;
  
  import static java.util.stream.Collectors.joining;
  
  import org.apache.commons.beanutils.PropertyUtils;
  
  public class ObjectMapperUtils {
  
      private static ObjectMapper objectMapper = new ObjectMapper();
  
      public static String convertToUrlEncoded(Object obj) {
          Map<String, String> map = objectMapper.convertValue(obj, Map.class);
  
          return map.keySet().stream()
                  .map(key -> {
                      try {
                          Class typeClass = PropertyUtils.getPropertyType(obj, key);
                          String type = typeClass.getSimpleName();
                          String value = null;
  
                          if (type.equals("String")) {
                              value = map.get(key);
                          } else if (typeClass.isPrimitive()) {
                              value = String.valueOf(map.get(key));
                          }
  
                          return value != null && value.length() > 0
                                  ? key + "=" + URLEncoder.encode(value, StandardCharsets.UTF_8.toString())
                                  : null;
                      } catch (UnsupportedEncodingException e) {
                          e.printStackTrace();
  
                          throw new UnsupportedOperationException(); // ???
                      } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                          e.printStackTrace();
                      }
  
                      return null;
                  })
                  .filter(value -> value != null)
                  .collect(joining("&"));
      }
  }

Usage Example

For example, we create a class that contains only primitive types. Then, we convert it to URL encoded form.

  package com.woolha.example.models;
  
  import lombok.AllArgsConstructor;
  import lombok.Builder;
  import lombok.Getter;
  import lombok.Setter;
  
  @Getter
  @Setter
  @AllArgsConstructor
  @Builder
  public class Item {
  
      private String name;
  
      private String description;
  
      private int quantity;
  
      private double price;
  
      private float priceFloat;
  
      private long code;
  
      private boolean isActive;
  
      private byte itemByte;
  
      private char firstLetter;
  
      private short id;
  }
  

abc

  package com.woolha.example;
  
  import com.woolha.example.models.Item;
  import com.woolha.example.utils.ObjectMapperUtils;
  
  public class ObjectMapperUtillsExample {
      public static void main(String[] args) {
          Item item = Item.builder()
                 .name("The string ü@foo-bar")
                 .description("Used to ")
                 .quantity(1000)
                 .itemByte(Byte.valueOf("65"))
                 .firstLetter('P')
                 .id(Short.valueOf("1"))
                 .price(2.5)
                 .priceFloat(Float.valueOf("2.5"))
                 .code(Long.valueOf("3"))
                 .isActive(false)
                 .build();
  
          System.out.println(ObjectMapperUtils.convertToUrlEncoded(item));
      }
  }

Below is the result

  name=The+string+%C3%BC%40foo-bar&description=Used+to+&quantity=1000&price=2.5&priceFloat=2.5&code=3&itemByte=65&firstLetter=P&id=1&active=false