SlideShare a Scribd company logo
URL Programming




Introduction
  How to write a program that fetches
  URL content

  How to write a program that submits
  GET or POST requests to a web server
  or a servlet
Start simply

 No programming involved!
   Connect to server (telnet)
   Send request (type in an http request)
   Get input

 Using TCP Sockets
   Connect to port 80
   Send HTTP request (GET, POST, HEAD)
   Read HTTP response




URL Programming In Java

 A URL is a name for a web resource (page, applet)
   http://www.cs.wmich.edu/index.html
 Java URL programming allows Java programs to access
 web resources by sending protocol requests and
 receiving protocol responses.
 Related Classes:
   URL class
   URLConnection class
   HttpURLConnection class
   URLEncoder class
URL Class
   Represents a Uniform Resource Locator
      scheme (protocol)
      hostname
      port
      path
      query string




 Parsing a URL

  You can use a URL object as a parser:

URL u = new URL(“http://www.cs.wmich.edu/index.html”);

System.out.println(“Proto:” + u.getProtocol());

System.out.println(“File:” + u.getFile());
Retrieving URL contents

 There are a number of ways to do this:

Object getContent();

InputStream openStream();

URLConnection openConnection();




Getting Header Information

 There are methods that return information
 extracted from response headers:
String getContentType();
String getContentLength();
long getLastModified();
URLConnection Class

   Represents the connection (not the URL
   itself).
   More control than URL
        can write to the connection (send POST data).
        can set request headers.
   HttpURLConnection is a subclass of
   URLConnection that is specific to HTTP




Example: Reading from a URL
// -- open connection
URL url = new URL(“http://www.google.com/index.html”);


HttpURLConnection conn = (HttpURLConnection)url.openConnection();


conn.connect();

// -- read in html ----------------
BufferedReader in =   new BufferedReader(new InputStreamReader(conn.getInputStream()));


String line;
String page = new String("");
while (null != ((line = in.readLine()))) {
   page += line;
}

in.close();
System.out.println(page);
Points to note

 An HttpURLConnection represents a
 connection to a particular page on a
 server, not just to the server.

 An HttpURLConnection object is NOT
 made by the usual use of new(). Instead it
 is created by the use of the Url’s
 openConnection() method




More points to note
 the connect method (of
 HttpURLConnection) not only opens the
 connection but also makes the GET
 request!

 the code for reading in the HTML from the
 connection is identical to that for reading in
 a file.
Faking GET Form Submission


 Not all webpages are produced in
 response to a simple GET request
 Some are the output of a program
    which may require parameters
 passed using the GET method (via the
 URL), e.g.
 http://www.cs.wmich.edu/servlet/convert?id=57&amount=10&units=pint




Faking POST Form Submission

 The POST request sends parameters
 (data) in the HTTP request body
 Any data to be sent must be encoded as a
 string of key-value pairs:
 id=57&amount=10&units=pint
URLEncoder Class

   Used to encode GET and POST parameters.

   Example:

String content = "action=“ + URLEncoder.encode("100”);

content += "&zipcode=“ + URLEncoder.encode(“49008");

content += "&name=“ + URLEncoder.encode(“Bill Somebody");

content += "&passwd=“ + URLEncoder.encode(“cisco");




  Making GET Form Submissions

   Step 1: Encode GET parameters
String content = "action=“ + URLEncoder.encode("100”);
content += "&zipcode=“ + URLEncoder.encode(“49008");
content += "&name=“ + URLEncoder.encode(“Bill Somebody");
content += "&passwd=“ + URLEncoder.encode(“cisco");
   Step 2: Make an HttpURLConnection object in the usual way:
URL url = new URL("http://www.cs.wmich.edu/servlet/converter“ + “?” + contents);
   Step 3:
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
   Step 4:
conn.connect();
   Step 5: You can read the reply as explained before.
Making POST Form Submissions

   Step 1: Encode POST parameters
String content = "action=“ + URLEncoder.encode("100”);
content += "&zipcode=“ + URLEncoder.encode(“49008");
content += "&name=“ + URLEncoder.encode(“Bill Somebody");
content += "&passwd=“ + URLEncoder.encode(“cisco");


   Step 2: Make an HttpURLConnection object in the usual way:
URL url = new URL("http://www.cs.wmich.edu/servlet/converter“);


   Step 3:
HttpURLConnection conn = (HttpURLConnection)url.openConnection();




  Making POST Form Submissions (Contd.)

  Step 4: Tell it that you want to use the POST method
conn.setRequestMethod("POST");
conn.setDoOutput(true);

   Step 5: Build a Printer writer to send things out via the connection
   and send the data.
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.println(content);
out.close();

    Step 6: You can read the reply as explained before.
Ad

Recommended

Servlets intro
Servlets intro
vantinhkhuc
 
Ajax chap 2.-part 1
Ajax chap 2.-part 1
Mukesh Tekwani
 
Ajax chap 3
Ajax chap 3
Mukesh Tekwani
 
AJAX
AJAX
Gouthaman V
 
Creating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat Application
Micha Kops
 
Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET Works
Randy Connolly
 
Introduction to Ajax programming
Introduction to Ajax programming
Fulvio Corno
 
async/await in Swift
async/await in Swift
Peter Friese
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
Michele Capra
 
Windows 8 metro applications
Windows 8 metro applications
Alex Golesh
 
Advanced #2 networking
Advanced #2 networking
Vitali Pekelis
 
Data models in Angular 1 & 2
Data models in Angular 1 & 2
Adam Klein
 
Chapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & Deitel
CSDeptSriKaliswariCo
 
The Big Picture and How to Get Started
The Big Picture and How to Get Started
guest1af57e
 
Testdrevet javautvikling på objektorienterte skinner
Testdrevet javautvikling på objektorienterte skinner
Truls Jørgensen
 
Bare-knuckle web development
Bare-knuckle web development
Johannes Brodwall
 
Introduction to ASP.Net Viewstate
Introduction to ASP.Net Viewstate
n|u - The Open Security Community
 
Intro to Parse
Intro to Parse
Tushar Acharya
 
Android - Saving data
Android - Saving data
Matteo Bonifazi
 
Sec.1 กล ม 1 เร__องการสร_างแบบฟอร_มและการส_งค_าต_วแปร
Sec.1 กล ม 1 เร__องการสร_างแบบฟอร_มและการส_งค_าต_วแปร
Bongza Naruk
 
W3 C11
W3 C11
DSKUMAR G
 
Android ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codes
Aravindharamanan S
 
Yogesh kumar kushwah represent’s
Yogesh kumar kushwah represent’s
Yogesh Kushwah
 
Remote code-with-expression-language-injection
Remote code-with-expression-language-injection
Mickey Jack
 
Ajax
Ajax
gauravashq
 
RicoAjaxEngine
RicoAjaxEngine
tutorialsruby
 
Simple Data Binding
Simple Data Binding
Doncho Minkov
 
What's Parse
What's Parse
Tsutomu Ogasawara
 
6 quan ly-tien_trinh
6 quan ly-tien_trinh
vantinhkhuc
 
4 quan ly-nguoi_dung
4 quan ly-nguoi_dung
vantinhkhuc
 

More Related Content

What's hot (20)

Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
Michele Capra
 
Windows 8 metro applications
Windows 8 metro applications
Alex Golesh
 
Advanced #2 networking
Advanced #2 networking
Vitali Pekelis
 
Data models in Angular 1 & 2
Data models in Angular 1 & 2
Adam Klein
 
Chapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & Deitel
CSDeptSriKaliswariCo
 
The Big Picture and How to Get Started
The Big Picture and How to Get Started
guest1af57e
 
Testdrevet javautvikling på objektorienterte skinner
Testdrevet javautvikling på objektorienterte skinner
Truls Jørgensen
 
Bare-knuckle web development
Bare-knuckle web development
Johannes Brodwall
 
Introduction to ASP.Net Viewstate
Introduction to ASP.Net Viewstate
n|u - The Open Security Community
 
Intro to Parse
Intro to Parse
Tushar Acharya
 
Android - Saving data
Android - Saving data
Matteo Bonifazi
 
Sec.1 กล ม 1 เร__องการสร_างแบบฟอร_มและการส_งค_าต_วแปร
Sec.1 กล ม 1 เร__องการสร_างแบบฟอร_มและการส_งค_าต_วแปร
Bongza Naruk
 
W3 C11
W3 C11
DSKUMAR G
 
Android ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codes
Aravindharamanan S
 
Yogesh kumar kushwah represent’s
Yogesh kumar kushwah represent’s
Yogesh Kushwah
 
Remote code-with-expression-language-injection
Remote code-with-expression-language-injection
Mickey Jack
 
Ajax
Ajax
gauravashq
 
RicoAjaxEngine
RicoAjaxEngine
tutorialsruby
 
Simple Data Binding
Simple Data Binding
Doncho Minkov
 
What's Parse
What's Parse
Tsutomu Ogasawara
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
Michele Capra
 
Windows 8 metro applications
Windows 8 metro applications
Alex Golesh
 
Advanced #2 networking
Advanced #2 networking
Vitali Pekelis
 
Data models in Angular 1 & 2
Data models in Angular 1 & 2
Adam Klein
 
Chapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & Deitel
CSDeptSriKaliswariCo
 
The Big Picture and How to Get Started
The Big Picture and How to Get Started
guest1af57e
 
Testdrevet javautvikling på objektorienterte skinner
Testdrevet javautvikling på objektorienterte skinner
Truls Jørgensen
 
Bare-knuckle web development
Bare-knuckle web development
Johannes Brodwall
 
Sec.1 กล ม 1 เร__องการสร_างแบบฟอร_มและการส_งค_าต_วแปร
Sec.1 กล ม 1 เร__องการสร_างแบบฟอร_มและการส_งค_าต_วแปร
Bongza Naruk
 
Android ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codes
Aravindharamanan S
 
Yogesh kumar kushwah represent’s
Yogesh kumar kushwah represent’s
Yogesh Kushwah
 
Remote code-with-expression-language-injection
Remote code-with-expression-language-injection
Mickey Jack
 

Viewers also liked (20)

6 quan ly-tien_trinh
6 quan ly-tien_trinh
vantinhkhuc
 
4 quan ly-nguoi_dung
4 quan ly-nguoi_dung
vantinhkhuc
 
Bai4
Bai4
vantinhkhuc
 
Bai 5
Bai 5
vantinhkhuc
 
Chude01 nhom10_TỔNG QUAN VỀ ELEARNING_VERSION2
Chude01 nhom10_TỔNG QUAN VỀ ELEARNING_VERSION2
Tuyen VI
 
Mhst- 2013 14 Nghiên cứu triển khai hệ thống MOOC cho Việt Nam dựa trên...
Mhst- 2013 14 Nghiên cứu triển khai hệ thống MOOC cho Việt Nam dựa trên...
Vu Hung Nguyen
 
Phan 1 mooc nen tang ket noi tri thuc (omt)
Phan 1 mooc nen tang ket noi tri thuc (omt)
Nguyen Hung
 
Chủ đề 1.tổng quan về elearning
Chủ đề 1.tổng quan về elearning
Shinji Huy
 
Báo cáo chủ đề 1: Tổng quan về e-learning
Báo cáo chủ đề 1: Tổng quan về e-learning
Thi Thanh Thuan Tran
 
Url (uniform resource locator)
Url (uniform resource locator)
Ben Lee
 
URL Presentation
URL Presentation
vRudd
 
Url
Url
bhylenia
 
Url Presentation
Url Presentation
sanniii
 
Software engineering presentation
Software engineering presentation
MJ Ferdous
 
An introduction to software engineering
An introduction to software engineering
Carlos Gavidia-Calderon
 
Software Engineering ppt
Software Engineering ppt
shruths2890
 
Annual Report - Mr. Pravin Ujjain
Annual Report - Mr. Pravin Ujjain
abciindia
 
豊橋の看板屋さんのパネル看板事例集
豊橋の看板屋さんのパネル看板事例集
illumi kanban
 
Presentation constructing an information panel
Presentation constructing an information panel
doogstone
 
Teaching manual of surumi. k
Teaching manual of surumi. k
Sano Anil
 
6 quan ly-tien_trinh
6 quan ly-tien_trinh
vantinhkhuc
 
4 quan ly-nguoi_dung
4 quan ly-nguoi_dung
vantinhkhuc
 
Chude01 nhom10_TỔNG QUAN VỀ ELEARNING_VERSION2
Chude01 nhom10_TỔNG QUAN VỀ ELEARNING_VERSION2
Tuyen VI
 
Mhst- 2013 14 Nghiên cứu triển khai hệ thống MOOC cho Việt Nam dựa trên...
Mhst- 2013 14 Nghiên cứu triển khai hệ thống MOOC cho Việt Nam dựa trên...
Vu Hung Nguyen
 
Phan 1 mooc nen tang ket noi tri thuc (omt)
Phan 1 mooc nen tang ket noi tri thuc (omt)
Nguyen Hung
 
Chủ đề 1.tổng quan về elearning
Chủ đề 1.tổng quan về elearning
Shinji Huy
 
Báo cáo chủ đề 1: Tổng quan về e-learning
Báo cáo chủ đề 1: Tổng quan về e-learning
Thi Thanh Thuan Tran
 
Url (uniform resource locator)
Url (uniform resource locator)
Ben Lee
 
URL Presentation
URL Presentation
vRudd
 
Url Presentation
Url Presentation
sanniii
 
Software engineering presentation
Software engineering presentation
MJ Ferdous
 
Software Engineering ppt
Software Engineering ppt
shruths2890
 
Annual Report - Mr. Pravin Ujjain
Annual Report - Mr. Pravin Ujjain
abciindia
 
豊橋の看板屋さんのパネル看板事例集
豊橋の看板屋さんのパネル看板事例集
illumi kanban
 
Presentation constructing an information panel
Presentation constructing an information panel
doogstone
 
Teaching manual of surumi. k
Teaching manual of surumi. k
Sano Anil
 
Ad

Similar to Url programming (20)

21servers And Applets
21servers And Applets
Adil Jafri
 
Cgi
Cgi
DEEPIKA KAMBOJ
 
Client-Server
Client-Server
Ahsanul Karim
 
Rpi python web
Rpi python web
sewoo lee
 
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
SharePoint Saturday NY
 
Asp.net server control
Asp.net server control
Sireesh K
 
Ajax
Ajax
Yoga Raja
 
T2
T2
Mo Ch
 
URL Class in Java.pdf
URL Class in Java.pdf
SudhanshiBakre1
 
Web Development with NodeJS
Web Development with NodeJS
Riza Fahmi
 
Html intake 38 lect1
Html intake 38 lect1
ghkadous
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Claire Townend Gee
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
DEVCON
 
Web Technologies - forms and actions
Web Technologies - forms and actions
Aren Zomorodian
 
Java web programming
Java web programming
Ching Yi Chan
 
Copy of cgi
Copy of cgi
Abhishek Kesharwani
 
Automating Cloud Operations: Everything You Wanted to Know about cURL and REST
Automating Cloud Operations: Everything You Wanted to Know about cURL and REST
Revelation Technologies
 
servlets
servlets
Arjun Shanka
 
Introduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST API
Rob Windsor
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
Cosmin Mereuta
 
21servers And Applets
21servers And Applets
Adil Jafri
 
Rpi python web
Rpi python web
sewoo lee
 
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
SharePoint Saturday NY
 
Asp.net server control
Asp.net server control
Sireesh K
 
Web Development with NodeJS
Web Development with NodeJS
Riza Fahmi
 
Html intake 38 lect1
Html intake 38 lect1
ghkadous
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Claire Townend Gee
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
DEVCON
 
Web Technologies - forms and actions
Web Technologies - forms and actions
Aren Zomorodian
 
Java web programming
Java web programming
Ching Yi Chan
 
Automating Cloud Operations: Everything You Wanted to Know about cURL and REST
Automating Cloud Operations: Everything You Wanted to Know about cURL and REST
Revelation Technologies
 
Introduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST API
Rob Windsor
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
Cosmin Mereuta
 
Ad

More from vantinhkhuc (20)

Servlet sessions
Servlet sessions
vantinhkhuc
 
Security overview
Security overview
vantinhkhuc
 
Rmi
Rmi
vantinhkhuc
 
Lecture17
Lecture17
vantinhkhuc
 
Lecture11 b
Lecture11 b
vantinhkhuc
 
Lecture10
Lecture10
vantinhkhuc
 
Lecture9
Lecture9
vantinhkhuc
 
Lecture6
Lecture6
vantinhkhuc
 
Jsse
Jsse
vantinhkhuc
 
Jsf intro
Jsf intro
vantinhkhuc
 
Jsp examples
Jsp examples
vantinhkhuc
 
Jpa
Jpa
vantinhkhuc
 
Ejb examples
Ejb examples
vantinhkhuc
 
Corba
Corba
vantinhkhuc
 
Ajax
Ajax
vantinhkhuc
 
Ejb intro
Ejb intro
vantinhkhuc
 
Chc6b0c6a1ng 12
Chc6b0c6a1ng 12
vantinhkhuc
 
Ch06
Ch06
vantinhkhuc
 
Ajas11 alok
Ajas11 alok
vantinhkhuc
 

Url programming

  • 1. URL Programming Introduction How to write a program that fetches URL content How to write a program that submits GET or POST requests to a web server or a servlet
  • 2. Start simply No programming involved! Connect to server (telnet) Send request (type in an http request) Get input Using TCP Sockets Connect to port 80 Send HTTP request (GET, POST, HEAD) Read HTTP response URL Programming In Java A URL is a name for a web resource (page, applet) http://www.cs.wmich.edu/index.html Java URL programming allows Java programs to access web resources by sending protocol requests and receiving protocol responses. Related Classes: URL class URLConnection class HttpURLConnection class URLEncoder class
  • 3. URL Class Represents a Uniform Resource Locator scheme (protocol) hostname port path query string Parsing a URL You can use a URL object as a parser: URL u = new URL(“http://www.cs.wmich.edu/index.html”); System.out.println(“Proto:” + u.getProtocol()); System.out.println(“File:” + u.getFile());
  • 4. Retrieving URL contents There are a number of ways to do this: Object getContent(); InputStream openStream(); URLConnection openConnection(); Getting Header Information There are methods that return information extracted from response headers: String getContentType(); String getContentLength(); long getLastModified();
  • 5. URLConnection Class Represents the connection (not the URL itself). More control than URL can write to the connection (send POST data). can set request headers. HttpURLConnection is a subclass of URLConnection that is specific to HTTP Example: Reading from a URL // -- open connection URL url = new URL(“http://www.google.com/index.html”); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.connect(); // -- read in html ---------------- BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; String page = new String(""); while (null != ((line = in.readLine()))) { page += line; } in.close(); System.out.println(page);
  • 6. Points to note An HttpURLConnection represents a connection to a particular page on a server, not just to the server. An HttpURLConnection object is NOT made by the usual use of new(). Instead it is created by the use of the Url’s openConnection() method More points to note the connect method (of HttpURLConnection) not only opens the connection but also makes the GET request! the code for reading in the HTML from the connection is identical to that for reading in a file.
  • 7. Faking GET Form Submission Not all webpages are produced in response to a simple GET request Some are the output of a program which may require parameters passed using the GET method (via the URL), e.g. http://www.cs.wmich.edu/servlet/convert?id=57&amount=10&units=pint Faking POST Form Submission The POST request sends parameters (data) in the HTTP request body Any data to be sent must be encoded as a string of key-value pairs: id=57&amount=10&units=pint
  • 8. URLEncoder Class Used to encode GET and POST parameters. Example: String content = "action=“ + URLEncoder.encode("100”); content += "&zipcode=“ + URLEncoder.encode(“49008"); content += "&name=“ + URLEncoder.encode(“Bill Somebody"); content += "&passwd=“ + URLEncoder.encode(“cisco"); Making GET Form Submissions Step 1: Encode GET parameters String content = "action=“ + URLEncoder.encode("100”); content += "&zipcode=“ + URLEncoder.encode(“49008"); content += "&name=“ + URLEncoder.encode(“Bill Somebody"); content += "&passwd=“ + URLEncoder.encode(“cisco"); Step 2: Make an HttpURLConnection object in the usual way: URL url = new URL("http://www.cs.wmich.edu/servlet/converter“ + “?” + contents); Step 3: HttpURLConnection conn = (HttpURLConnection)url.openConnection(); Step 4: conn.connect(); Step 5: You can read the reply as explained before.
  • 9. Making POST Form Submissions Step 1: Encode POST parameters String content = "action=“ + URLEncoder.encode("100”); content += "&zipcode=“ + URLEncoder.encode(“49008"); content += "&name=“ + URLEncoder.encode(“Bill Somebody"); content += "&passwd=“ + URLEncoder.encode(“cisco"); Step 2: Make an HttpURLConnection object in the usual way: URL url = new URL("http://www.cs.wmich.edu/servlet/converter“); Step 3: HttpURLConnection conn = (HttpURLConnection)url.openConnection(); Making POST Form Submissions (Contd.) Step 4: Tell it that you want to use the POST method conn.setRequestMethod("POST"); conn.setDoOutput(true); Step 5: Build a Printer writer to send things out via the connection and send the data. PrintWriter out = new PrintWriter(conn.getOutputStream()); out.println(content); out.close(); Step 6: You can read the reply as explained before.