简体   繁体   中英

Java String formatting for a REST API url

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%2C%2053.64577%2C%20-2.06653%2C%2053.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%2C%20%f%2C%20%f%2C%20%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.

Since you've %2C 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 = "%2C%20";
    String vmDataFeedUrlPatternWithBB = "datafeed?boundingbox="+a+COMMA+b+COMMA+c+COMMA+d;
    System.out.println(vmDataFeedUrlPatternWithBB);

OUTPUT:

datafeed?boundingbox=53.64577%2C%202.73389%2C%2053.93593%2C%20-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%2C2.733890%2C53.935930%2C-2.066530

You need to escape the % symbol for the URL 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%%2C%%20%f%%2C%%20%f%%2C%%20%f";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM