简体   繁体   English

具有URL编码参数的Java URL编码

[英]Java URL encoding with url encode parameters

How to encode in Java this String 如何在Java中对此字符串进行编码

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 encode this String like this: java.net.URLEncoder将此字符串编码如下:

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..

I expect this result: 我期望这个结果:

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..

I think following code can help you: 我认为以下代码可以帮助您:

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

I do not want to encode encoded part of String. 我不想对String的编码部分进行编码。 Needs a universal algorithm. 需要通用算法。 String is not always encoded fragmentarily 字符串并非总是零碎编码

I think universal algorithm is impossible in that case, what you can do that find encoded part manually and not encoded it again (see code above). 我认为在那种情况下通用算法是不可能的,您可以手动找到已编码的部分而不进行再次编码(请参见上面的代码)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM