Java Utililty Methods URL Connection

List of utility methods to do URL Connection

Description

The list of methods to do URL Connection are organized into topic(s).

Method

StringsendGetRequest(String urlStr)
send Get Request
try {
    URL url = new URL(urlStr);
    URLConnection conn = url.openConnection();
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
...
StringsendPost(String url, String param)
send Post
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
    URL realUrl = new URL(url);
    URLConnection conn = realUrl.openConnection();
    conn.setRequestProperty("accept", "*/*");
    conn.setRequestProperty("connection", "Keep-Alive");
...
voidsetTimeout(URLConnection conn, int milliseconds)
set Timeout
conn.setConnectTimeout(milliseconds);
voidsetTimeouts(URLConnection connection)
Sets timeout parameters on the given URLConnection.
connection.setConnectTimeout(SOCKET_TIMEOUT);
connection.setReadTimeout(SOCKET_TIMEOUT);
StringshortenUrl(String url)
shorten Url
String shortUrl = "";
try {
    URLConnection conn = new URL("https://www.googleapis.com/urlshortener/v1/url").openConnection();
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Type", "application/json");
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write("{\"longUrl\":\"" + url + "\"}");
    wr.flush();
...
voidskip(URLConnection connection, long count)
skip
try {
    InputStream is = connection.getInputStream();
    while (count-- > 0) {
        is.read();
} catch (IOException ignored) {
StringslurpStream(URLConnection conn)
slurp Stream
String ret = EMPTY;
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
char[] tmp = new char[8192];
int r;
while ((r = in.read(tmp, 0, 8192)) != -1) {
    ret += new String(tmp, 0, r);
in.close();
...
StringslurpURL(URL u, String encoding)
Returns all the text at the given URL.
String lineSeparator = System.getProperty("line.separator");
URLConnection uc = u.openConnection();
uc.setReadTimeout(30000);
InputStream is;
try {
    is = uc.getInputStream();
} catch (SocketTimeoutException e) {
    System.err.println("Time out. Return empty string");
...
StringslurpURLNoExceptions(URL u)
Returns all the text at the given URL.
try {
    return slurpURL(u);
} catch (Exception e) {
    e.printStackTrace();
    return null;
Listurl2list(String sURL, String encoding)
urllist
try {
    URL url = new URL(sURL);
    URLConnection conn = url.openConnection();
    InputStream is = conn.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding));
    List<String> list = new ArrayList<String>();
    String line;
    while ((line = br.readLine()) != null) {
...