Java program to access an URL
Hi Everyone, in this blog post I will be writing a java program to access an URL. The Java program to connect to an URL is as follows:
package com.blog.techjourney; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class AccessURL { public static void main(String[] args) { String url = "http://sujithforu.blogspot.com/"; String fakeurl = "http://thisisanincorrecttypeofurl.com/"; System.out.println(" Connecting to existing url - "+url); getURLResponse(url); System.out.println(); System.out.println(" Connecting to fake url - "+fakeurl); getURLResponse(fakeurl); } public static void getURLResponse(String str) { URL url; URLConnection urlConnection; HttpURLConnection httpConnection = null; try { url = new URL(str); urlConnection = url.openConnection(); urlConnection.connect(); System.out.println("Connected to "+url); httpConnection = (HttpURLConnection) urlConnection; int responseCode = httpConnection.getResponseCode(); System.out.println("Response Code= " + responseCode + " for "+ url.toString()); httpConnection.disconnect(); } catch (MalformedURLException mue) { System.out.println("MalformedURLException in URLConnection "); httpConnection.disconnect(); } catch(IOException ioe){ System.out.println("IOException in URLConnection "); httpConnection.disconnect(); }catch(Exception e){ System.out.println("Exception in URLConnection "); httpConnection.disconnect(); } } }
The output of the program is as follows:
Connecting to existing url - http://sujithforu.blogspot.com/ Connected to http://sujithforu.blogspot.com/ Response Code= 200 for http://sujithforu.blogspot.com/ Connecting to fake url - http://thisisanincorrecttypeofurl.com/ IOException in URLConnection Exception in thread "main" java.lang.NullPointerException at com.blog.techjourney.AccessURL.getURLResponse(AccessURL.java:42) at com.blog.techjourney.AccessURL.main(AccessURL.java:18)
Thank you for reading the post. Do comment below.
This comment has been removed by a blog administrator.
ReplyDelete