Java中的String.format的UnknownFormatConversionException

时间:2013-03-12 16:17:48

标签: java

为什么我收到错误java.util.UnknownConversionException:Conversion =' D'对于下面的方法。我创建一个初始字符串,然后从一个方法返回它来做一个String.format。它发生在String.format。

String url = StringUtils.join(new String[] { BASE_URL,
                "/location/inst/", slug,
                "/coursesections/number%s.json?apiKey=", apiKey,
                "&token=", GetAuthTokenEncoded(authToken) })


String url2 = String.format(url, ("/" + callNumber));

StringUtils的输出

http://test.com/location/inst/testy/coursesections/number%s;.json?apiKey=dfsdfsdfsadfsdf&token=2.0%7Cidm%7Cidm%7Ctest%3Dbesrlin_50d4s9dd25dsee56f3a1e95fb4f%26berlin%3D50d49dd2e2f28cf450b0caa9f449%26campus%3Dberlin%3A50d49dd25ee56f3a1e95fb4f%7C2013-03-12T16%3A25%3A23%2B00%3A00%7C2013-03-12T19%3A25%3A23%2B00%3A00%7C09161a6011f2dc2e3443bc40b2d3f4b3d4f

2 个答案:

答案 0 :(得分:2)

GetAuthTokenEncoded(authToken)包含导致错误的整个%。为什么不以与加入其余字符串相同的方式附加callNumber?

String url = StringUtils.join(new String[] { BASE_URL,
            "/location/inst/", part,
            "/coursesections/number/", number, ".json?apiKey=", apiKey,
            "&token=", GetAuthTokenEncoded(authToken) })

答案 1 :(得分:1)

由于网址转义,要格式化的url字符串中存在“%3D”。您需要将GetAuthTokenEncoded的结果作为参数提供给String.format,因此它不会将“%3D”解释为占位符。

String url = StringUtils.join(new String[] { BASE_URL,
            "/location/inst/", part,
            "/coursesections/number%s.json?apiKey=", apiKey,
            "&token=%s");
String url2 = String.format(url, ("/" + callNumber), GetAuthTokenEncoded(authToken));