Skip to content

Instantly share code, notes, and snippets.

@mlaccetti
Created March 21, 2012 02:20
Show Gist options
  • Save mlaccetti/2143792 to your computer and use it in GitHub Desktop.
Save mlaccetti/2143792 to your computer and use it in GitHub Desktop.
Java 7 URL connection
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.net.URLConnection;
public class CustomHttpUrlConnection implements Serializable, AutoCloseable {
private final URLConnection conn;
public CustomHttpUrlConnection(String url) throws IOException {
conn = new URL(url).openConnection();
conn.connect();
}
public InputStream getInputStream() throws IOException {
return conn.getInputStream();
}
@Override
public void close() throws IOException {
getInputStream().close();
}
}
final StringBuffer json = new StringBuffer();
try (CustomHttpUrlConnection conn = new CustomHttpUrlConnection(url); InputStream in = conn.getInputStream()) {
int b = 0;
while (b != -1) {
b = in.read();
json.append((char)b);
}
} catch (Exception ex) {
log.error("Could not retrieve information from remote server.", ex);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment