Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Encoding of a mailto link with subject and plain text multiline body

I´ve googled a lot, but I wasn´t able to find a solution to my problem. I need to encode a mailto: link with subject and body to UTF-8 in java.

The body consists of plain text

Is there any method which encodes:

  • the whole string in UTF-8, for example Ä to %C3%84S
  • blanks into %20 instead of +
  • \r\n into %0D%0A
  • / to %2f

Thank you for your help!

like image 758
Ernst Avatar asked Oct 17 '25 03:10

Ernst


1 Answers

You want the URLEncode.encode(String s, String enc) method. The second parameter should be the string UTF-8.

It does encode spaces as + instead of %20, which is valid for query parameters; you can always just special-case that and replace all of the former with the latter. Example:

import java.net.URLEncoder;
import java.util.regex.Pattern;

public class Foobar {
  private static Pattern space = Pattern.compile("\\+");
  public static void main(String[] args) throws Exception {
    String first = URLEncoder.encode("Ä+ \r\n/", "UTF-8");
    String second = space.matcher(first).replaceAll("%20");
    System.out.println(second);
  }
}

This outputs:

%C3%84%2B%20%0D%0A%2F
like image 85
wmorrell Avatar answered Oct 19 '25 15:10

wmorrell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!