0

The user can set a number of values (which are optional) for a search query that will be passed on to a REST api. So I create a POJO to hold all the set values like

class Search{

  private String minPrice; 
  private String maxPrice; 
  private String category; 
  // etc.pp.

}

When I construct the URL for the api call, i have to check wether that value is set all the time like

if (search.getMinPrice() != null){

  url.append("&minprice=" + search.getMinPrice());

}

Is there a more convenient/ elegant way to do this

  1. with pure Java, just a way to "do sth if sth is not null"
  2. or even a library/tool that lets you construct Urls from objects?
fweigl
  • 21,278
  • 20
  • 114
  • 205
  • I think you mean query strings more specifically than URLs. Constructing an arbitrary URL from an object would be impossible. However, constructing a query string from members of a class would be possible. – rmlan Mar 14 '13 at 13:36
  • Also, possible duplicates of http://stackoverflow.com/questions/1861620/is-there-a-java-package-to-handle-building-urls and http://stackoverflow.com/questions/1405731/is-there-a-java-method-that-encodes-a-collection-of-parameters-as-a-url-query-com – rmlan Mar 14 '13 at 13:38

1 Answers1

1

Something like:

String url = "http://base.com/some/path?" + (maxPrice==null ? "" : "maxPrice="+maxPrice);
CodeChimp
  • 8,016
  • 5
  • 41
  • 79