Java httpURLConnection example

This code will connect to a given URL and gets the content if the response is a success.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpClient {
  
  private static final String USER_AGENT = "Mozilla/5.0";
  
  public static void main(String[] args) {
    
    String host = "http://tutoref.com";
    try {
      
      URL url = new URL(host);
      HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
      
      // specify request header
      httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
      
      // get response code, 200 = Success
      int responseCode = httpURLConnection.getResponseCode();
      System.out.println(responseCode);
      
      // if response == 200, display the content
      if(responseCode==200){
        System.out.println(httpURLConnection.getContent().toString());
        BufferedReader br = 
           new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream())
           );
        String line=null;
        while((line = br.readLine())!= null){
          System.out.println(line);
        }
      }
      
      
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}

 

 

You like this content ? Share it with you entourage !

Leave a Reply

Your email address will not be published.