2017-06-29 92 views
0

如何在Java中,這串與URL編碼的Java URL編碼參數

http://demo.pl/sample?id=tests%trg=https%3A%2F%2Fwww.google.com%sample.html%3Fwmc%3DAFF48+_LS.%23%7NUMBER_ID%7D_%23%7NUMBER_ID%7D.. 

java.net.URLEncoder中編碼此String這樣的編碼:

http%3A%2F%2Fdemo.pl%2Fsample%3Fid%3Dtests%25trg%3Dhttps%253A%252F%252Fwww.google.com%25sample.html%253Fwmc%253DAFF48%2B_LS.%2523%257NUMBER_ID%257D_%2523%257NUMBER_ID%257D.. 

我期待這樣的結果:

http%3A%2F%2Fdemo.pl%2Fsample%3Fid%3Dtests%25trg%3Dhttps%3A%2F%2Fwww.google.com%sample.html%3Fwmc%3DAFF48+_LS.%23%7NUMBER_ID%7D_%23%7NUMBER_ID%7D.. 
+0

所以你只想要一部分字符串編碼,實際上? –

+0

我不想編碼String的編碼部分。需要一個通用算法。字符串並不總是以片段形式編碼 – Wait

回答

2

我覺得下面的代碼可以幫到你:

String s = "http://demo.pl/sample?id=tests%trg=https%3A%2F%2Fwww.google.com%sample.html%3Fwmc%3DAFF48+_LS.%23%7NUMBER_ID%7D_%23%7NUMBER_ID%7D"; 
int i = s.indexOf("%"); 
String result1 = URLEncoder.encode(s.substring(0, i)) + "%25" + s.substring(i + 1); 
System.out.println(result1); // print http%3A%2F%2Fdemo.pl%2Fsample%3Fid%3Dtests%25trg=https%3A%2F%2Fwww.google.com%sample.html%3Fwmc%3DAFF48+_LS.%23%7NUMBER_ID%7D_%23%7NUMBER_ID%7D 

我不想編碼字符串的編碼部分。需要通用的 算法。字符串並不總是編碼零星

我認爲通用算法,在這種情況下是不可能的,你可以再做一次發現編碼部分手動和未編碼(見上面的代碼)。