我在使用非 ASCII 和空格组合对 url 进行编码时遇到问题。例如,http://xxx.xx.xx.xx/resources/upload/pdf/APPLE ははは.pdf
。我读过here您只需要对 url 路径的最后部分进行编码。
代码如下:
public static String getLastPathFromUrl(String url) {
return url.replaceFirst(".*/([^/?]+).*", "$1");
}
现在我已经有了 APPLE ははは.pdf
,下一步是将空格替换为 %20
以使链接正常工作但是 问题是,如果我编码 APPLE%20ははは.pdf
它会变成 APPLE%2520%E3%81%AF%E3%81%AF%E3%81%AF。 pdf
. 我应该有 APPLE%20%E3%81%AF%E3%81%AF%E3%81%AF.pdf
。
所以我决定:
1. Separate each word from the link
2. Encode it
3. Concatenate the new encoded words, for example:
3.A. APPLE (APPLE)
3.B. %E3%81%AF%E3%81%AF%E3%81%AF.pdf (ははは.pdf)
with the (space) converted to %20, now becomes APPLE%20%E3%81%AF%E3%81%AF%E3%81%AF.pdf
这是我的代码:
public static String[] splitWords(String sentence) {
String[] words = sentence.split(" ");
return words;
}
调用代码:
String urlLastPath = getLastPathFromUrl(pdfUrl);
String[] splitWords = splitWords(urlLastPath);
for (String word : splitWords) {
String urlEncoded = URLEncoder.encode(word, "utf-8"); //STUCKED HERE
}
我现在想连接索引内的每个unicoded字符串(urlEncoded
),最终形成像APPLE%20%E3%81%AF%E3%81%AF%E3%81 %AF.pdf
。我该怎么做?
最佳答案
实际上 %20 被编码为 %2520 所以只需调用 URLEncoder.encode(word, "utf-8");所以你会得到像这样的结果 APPLE+%E3%81%AF%E3%81%AF%E3%81%AF.pdf 并在最终结果中将 + 替换为 %20。
关于java - 如何在每个字符串索引内连接字符串或单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21548049/