Home > Software engineering >  Java String formatting for a REST API url
Java String formatting for a REST API url

Time:01-18

I am trying to format a URL in Java using String.format. The API takes the parameters of the following form:

datafeed?boundingBox=-2.73389, 53.64577, -2.06653, 53.93593

So, I am trying something like:

public class MyClass {
    public static void main(String args[]) {
      double a = 53.64577;
      double b = 2.73389;
      double c = 53.93593;
      double d = -2.06653;
      
      String vmDataFeedUrlPatternWithBB = "datafeed?boundingbox=%f, %f, %f, %f";

      System.out.println(String.format(vmDataFeedUrlPatternWithBB,a, b, c, d));
    }
}

However, this is having issues and results in:

Exception in thread "main" java.util.IllegalFormatConversionException: c != java.lang.Double

Maybe I need to convert the comma and space separately but have not been able to figure this out.

CodePudding user response:

Since you've , in the String format expression it's treated as a character and expecting a character value hence it's not working as expected.

To solve this problem you've 2 options:

1) String Contactenation:

    final String COMMA = ", ";
    String vmDataFeedUrlPatternWithBB = "datafeed?boundingbox=" a COMMA b COMMA c COMMA d;
    System.out.println(vmDataFeedUrlPatternWithBB);

OUTPUT:

datafeed?boundingbox=53.64577, 2.73389, 53.93593, -2.06653

2) Use URLEncoder

    String vmDataFeedUrlPatternWithBB = "datafeed?boundingbox=";
    String values = "%f,%f,%f,%f";

    String s = String.format(values, a, b, c, d);

    try {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        String finalValue = vmDataFeedUrlPatternWithBB   encode;
        System.out.println(finalValue);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

OUTPUT:

datafeed?boundingbox=53.645770,2.733890,53.935930,-2.066530

CodePudding user response:

You need to escape the % symbol for the utl characters that are not part of the string formatting. You escape it by duplicating it %%. So try with this pattern instead:

String vmDataFeedUrlPatternWithBB = "datafeed?boundingbox=%f%,% %f%,% %f%,% %f";
  •  Tags:  
  • Related