Get response code from a URL in Java

Description

The following code shows how to get response code from a URL.

Example


// ww  w .j a va  2  s . c  o  m
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class Main{
  public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.google.com");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();


    System.out.println("Response code is " + httpCon.getResponseCode());
 }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Network »




NetworkInterface
URI
URL
HTTP
HTTP Read
IP
Socket
UDP
URL Encode