Created
November 15, 2015 08:14
-
-
Save DenWav/5478fed4df5065f98430 to your computer and use it in GitHub Desktop.
Woot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String encode(String input) { | |
StringBuilder resultStr = new StringBuilder(); | |
for (char ch : input.toCharArray()) { | |
if (isUnsafe(ch)) { | |
resultStr.append('%'); | |
resultStr.append(toHex(ch / 16)); | |
resultStr.append(toHex(ch % 16)); | |
} else { | |
resultStr.append(ch); | |
} | |
} | |
return resultStr.toString(); | |
} | |
private static char toHex(int ch) { | |
return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10); | |
} | |
private static boolean isUnsafe(char ch) { | |
return ch > 128 || ch < 0 || " %$&+,/:;=?@<>#%".indexOf(ch) >= 0; | |
} | |
public static String getTextFromUrl(URL url) throws IOException { | |
URLConnection con = url.openConnection(); | |
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)"); | |
InputStream in = con.getInputStream(); | |
String encoding = con.getContentEncoding(); | |
encoding = encoding == null ? "UTF-8" : encoding; | |
ByteArrayOutputStream baos = new ByteArrayOutputStream(); | |
byte[] buffer = new byte[8192]; | |
int len; | |
while ((len = in.read(buffer)) != -1) { | |
baos.write(buffer, 0, len); | |
} | |
return new String(baos.toByteArray(), encoding); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment