You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Path.getName()截断%25致URL解码失败,求解决方案

问题原因与解决方案

你的问题出在URI.getPath()会自动解码URL转义字符:原始URL里的%25是%的URL编码,调用getPath()时会把它解码成%,所以拿到的路径字符串已经是/api/v1/guests/Please+Submit+to+Any%,后续用Path处理自然就丢失了原始的%25编码,导致解码失败。

要保留原始编码的路径段,你需要用URI.getRawPath()替代getPath()——这个方法会返回未解码的原始路径字符串,不会转义任何字符。

修改后的代码如下:

import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;

public class UrlPathTest {
    public static void main(String[] args) {
        // 用getRawPath()获取未解码的原始路径
        var playerSrcPath = URI.create("https://www.speedrun.com/api/v1/guests/Please+Submit+to+Any%25").getRawPath();
        var path = Paths.get(playerSrcPath);
        var lastSegment = path.getName(path.getNameCount() - 1).toString();         
        System.out.println(lastSegment); // 输出: Please+Submit+to+Any%25

        // 现在可以正常解码,得到原始内容
        var playerAbbr = URLDecoder.decode(lastSegment, StandardCharsets.UTF_8);        
        System.out.println(playerAbbr); // 输出: Please Submit to Any%
    }
}

这样既保留了Path分割路径、自动忽略查询参数的优势,又能拿到完整的编码路径段,解码时不会报错。

内容的提问来源于stack exchange,提问作者mgmedick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 03:45:03