URLEncoder { public String encode(String path) { int maxBytesPerChar = 10; StringBuffer rewrittenPath = new StringBuffer(path.length()); ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar); OutputStreamWriter writer = null; try { writer = new OutputStreamWriter(buf, "UTF8"); } catch (Exception e) { e.printStackTrace(); writer = new OutputStreamWriter(buf); } for (int i = 0; i < path.length(); i++) { int c = path.charAt(i); if (safeCharacters.get(c) || !isPureAscii(path.charAt(i))) { rewrittenPath.append((char)c); } else { try { writer.write((char)c); writer.flush(); } catch (IOException e) { buf.reset(); continue; } byte[] ba = buf.toByteArray(); for (int j = 0; j < ba.length; j++) { byte toEncode = ba[j]; rewrittenPath.append('%'); int low = toEncode & 0x0f; int high = (toEncode & 0xf0) >> 4; rewrittenPath.append(hexadecimal[high]); rewrittenPath.append(hexadecimal[low]); } buf.reset(); } } return rewrittenPath.toString(); } URLEncoder(); String encode(String path); static boolean isPureAscii(Character v);  }
@Test public void encode() { Assert.assertEquals("%2Ftmp%2F", new URLEncoder().encode("/tmp/")); Assert.assertEquals("%20", new URLEncoder().encode(" ")); Assert.assertEquals("%5F", new URLEncoder().encode("_")); Assert.assertEquals("%25", new URLEncoder().encode("%")); }