简体   繁体   中英

Url encode a part of a string in java

I have a url in which I have few macros that I don't want to be encoded, but the remaining part should be. For example -

https://example.net/adaf/${ABC}/asd/${WSC}/ 

should be encoded as

https%3A%2F%2Fexample.net%2Fadaf%2F${ABC}%2Fasd%2F${WSC}%2F

URLEncoder.encode(string, encoding) encodes the entire string. I need a function of the sort - encode(string, start, end, encoding)

Is there any existing library which does this?

AFAIK no standard library provides overloaded method like this. But you can build a custom wrapper function around standard API.

To achieve your goal, code can look like:

public static void main(String[] args) throws UnsupportedEncodingException {
    String source = "https://example.net/adaf/${ABC}/asd/${WSC}/";
    String target = "https%3A%2F%2Fexample.net%2Fadaf%2F${ABC}%2Fasd%2F${WSC}%2F";

    String encodedUrl = encode(source, 0, 25, StandardCharsets.UTF_8.name()) +
            source.substring(25, 31) +
            encode(source, 31, 36, StandardCharsets.UTF_8.name()) +
            source.substring(36, 42) +
            encode(source, 42, 43, StandardCharsets.UTF_8.name());


    System.out.println(encodedUrl);
    System.out.println(encodedUrl.equals(target));
}

static String encode(String s, int start, int end, String encoding) throws UnsupportedEncodingException {
    return URLEncoder.encode(s.substring(start, end), StandardCharsets.UTF_8.name());
}

https%3A%2F%2Fexample.net%2Fadaf%2F${ABC}%2Fasd%2F${WSC}%2F

true

But this is going to be quite messy.

As an alternative you can simply replace charsets you don't want to escape with their original value after encoding:

public static void main(String[] args) throws UnsupportedEncodingException {
    String source = "https://example.net/adaf/${ABC}/asd/${WSC}/";
    String target = "https%3A%2F%2Fexample.net%2Fadaf%2F${ABC}%2Fasd%2F${WSC}%2F";

    String encodedUrl = URLEncoder.encode(source, StandardCharsets.UTF_8.name())
            .replaceAll("%24", "\\$")
            .replaceAll("%7B", "{")
            .replaceAll("%7D", "}");


    System.out.println(encodedUrl);
    System.out.println(encodedUrl.equals(target));
}

https%3A%2F%2Fexample.net%2Fadaf%2F${ABC}%2Fasd%2F${WSC}%2F

true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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