0

I have to build a request with Spring's RestTemplate where the url is composed like this:

base_url/rtv?from=2019-05-08T00%3A00%2B02%3A00

what goes after "from" query parameter is a date according to the ISO8601 format. I can't format a date, obtained via Calendar or via System.currentTimeMillis() to get the above url.

What I do is this:

// I get the date for the url
Calendar calendar = Calendar.getInstance();
calendar.set(2019, Calendar.MAY, 08, 24, 1, 1);
calendar.set(Calendar.MILLISECOND, 0);
Date date = calendar.getTime();

// Conversion of Date in String
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String fromString = sdf.format(date);
                
// I create the uri builder with my data with the query parameter after the base_url/rtv
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(base_url+"/rtv");
if (from != null)
    builder.queryParam("from", fromString);
        
// I create the headers for the call rest
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + token);
HttpEntity<String> entity = new HttpEntity<String>(headers);

// I make the call
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange(
    builder.buildAndExpand(urlMisurazioneStazione).toUri(),
    HttpMethod.GET,
    entity,
    String.class
);      

I get an url like this: base_url/rtv?from=2020-11-02T00:01:01.000+0100 which is different from the one requested, i.e. base_url/rtv?from=2019-05-08T00%3A00%2B02%3A00.

So, mine is (rtv?from=2019-05-08T00:01:01.000+0100) that is DIFFERENT from that requested (rtv?from=2019-05-08T00%3A00%2B02%3A00)

How do I get an url like the requested one (rtv?from=2019-05-08T00%3A00%2B02%3A00) starting from a date taken from Calendar or from a timestamp?

Thank you.

Alberto Deidda
  • 506
  • 1
  • 4
  • 13
  • 1
    Hi Alberto. Did you try using a Deserializer (as shown here for example: https://stackoverflow.com/questions/59838777/parsing-iso-date-string-into-zonedatetime-with-resttemplate-in-spring) to convert the date from Calendar to the format you're needing? – GuiFalourd Dec 01 '20 at 14:55
  • I recommend you don’t use `Calendar`, `Date` and `SimpleDateFormat`. Those classes are poorly designed and long outdated, the last in particular notoriously troublesome. Instead use `Instant` and/or `OffsetDateTime`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Dec 02 '20 at 18:13
  • Don’t prefix your numbers with 0. This line does not compile: `calendar.set(2019, Calendar.MAY, 08, 24, 1, 1);`. Also hour of day of 24 does not make sense, numbers go from 0 through 23. – Ole V.V. Dec 02 '20 at 20:07

0 Answers0