Skip to content

Instantly share code, notes, and snippets.

@don9z
Created February 19, 2013 09:04

Revisions

  1. don9z renamed this gist Feb 19, 2013. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. don9z created this gist Feb 19, 2013.
    20 changes: 20 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    public static String stringByAddingPercentEscapesUsingEncoding(String input, String encoding)
    throws UnsupportedEncodingException {
    byte[] inputBytes = input.getBytes(encoding);
    StringBuilder stringBuilder = new StringBuilder(inputBytes.length);
    for(int i = 0; i < inputBytes.length; ++i) {
    int charByte = inputBytes[i] < 0 ? inputBytes[i] + 256 : inputBytes[i];
    if( charByte <= 0x20 || charByte >= 0x7F ||
    (charByte == 0x22 || charByte == 0x25 || charByte == 0x3C ||
    charByte == 0x3E || charByte == 0x20 || charByte == 0x5B ||
    charByte == 0x5C || charByte == 0x5D || charByte == 0x5E ||
    charByte == 0x60 || charByte == 0x7b || charByte == 0x7c ||
    charByte == 0x7d)) {
    stringBuilder.append(String.format("%%%02X", charByte));
    }
    else {
    stringBuilder.append((char)charByte);
    }
    }
    return stringBuilder.toString();
    }