Skip to content

Commit d26c0fa

Browse files
authored
Merge pull request #576 from bigooio/FUSION-17975
解决 URLEncoder 空格为 + 号问题
2 parents 1e0189b + c97297b commit d26c0fa

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

src/main/java/com/qiniu/cdn/CdnManager.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,17 @@ public CdnManager(Auth auth, String server, Client client) {
5959
this.client = client;
6060
}
6161

62+
public static String encodePath(String path) throws Exception {
63+
try {
64+
return URLEncoder.encode(path, "UTF-8").replaceAll("%2F", "/").replaceAll("\\+", "%20");
65+
} catch (Exception e) {
66+
throw e;
67+
}
68+
}
69+
6270
public static String createTimestampAntiLeechUrl(URL oUrl, String encryptKey, long deadline) throws QiniuException {
6371
try {
64-
String urlencodedPath = URLEncoder.encode(oUrl.getPath(), "UTF-8").replaceAll("%2F", "/");
72+
String urlencodedPath = encodePath(oUrl.getPath());
6573
String query = oUrl.getQuery();
6674
String file = (query == null) ? urlencodedPath : (urlencodedPath + "?" + query);
6775
URL url = new URL(oUrl.getProtocol(), oUrl.getHost(), oUrl.getPort(), file);
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package test.com.qiniu.cdn;
2+
3+
import com.qiniu.cdn.CdnManager;
4+
import org.junit.jupiter.api.Test;
5+
6+
import static org.junit.jupiter.api.Assertions.assertEquals;
7+
import static org.junit.jupiter.api.Assertions.fail;
8+
9+
public class CdnManagerTest {
10+
@Test
11+
public void testencodePath() {
12+
try {
13+
// 空格替换为 %20
14+
String path = "/ hello/ world";
15+
String got = CdnManager.encodePath(path);
16+
String want = "/%20hello/%20world";
17+
assertEquals(want, got);
18+
19+
// 半角 + 号替换为 %2B
20+
path = "/+hello/+world";
21+
got = CdnManager.encodePath(path);
22+
want = "/%2Bhello/%2Bworld";
23+
24+
assertEquals(want, got);
25+
26+
// % 号替换为 %25
27+
path = "/%hello/+world";
28+
got = CdnManager.encodePath(path);
29+
want = "/%25hello/%2Bworld";
30+
assertEquals(want, got);
31+
32+
33+
} catch (Exception e) {
34+
fail(e.toString());
35+
}
36+
}
37+
38+
}

0 commit comments

Comments
 (0)