Created
          March 21, 2012 02:20 
        
      - 
      
- 
        Save mlaccetti/2143792 to your computer and use it in GitHub Desktop. 
    Java 7 URL connection
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | 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(); | |
| } | |
| } | 
  
    
      This file contains hidden or 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
    
  
  
    
  | 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