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.

More Related Content

PDF
Servlets intro
vantinhkhuc
 
PDF
Ajax chap 2.-part 1
Mukesh Tekwani
 
PDF
Ajax chap 3
Mukesh Tekwani
 
PPT
AJAX
Gouthaman V
 
ODP
Creating a Java EE 7 Websocket Chat Application
Micha Kops
 
PDF
Web II - 02 - How ASP.NET Works
Randy Connolly
 
PDF
Introduction to Ajax programming
Fulvio Corno
 
PDF
async/await in Swift
Peter Friese
 
Servlets intro
vantinhkhuc
 
Ajax chap 2.-part 1
Mukesh Tekwani
 
Ajax chap 3
Mukesh Tekwani
 
Creating a Java EE 7 Websocket Chat Application
Micha Kops
 
Web II - 02 - How ASP.NET Works
Randy Connolly
 
Introduction to Ajax programming
Fulvio Corno
 
async/await in Swift
Peter Friese
 

What's hot (20)

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

Viewers also liked (20)

PDF
6 quan ly-tien_trinh
vantinhkhuc
 
PDF
4 quan ly-nguoi_dung
vantinhkhuc
 
PDF
Bai4
vantinhkhuc
 
PDF
Bai 5
vantinhkhuc
 
PPTX
Chude01 nhom10_TỔNG QUAN VỀ ELEARNING_VERSION2
Tuyen VI
 
PDF
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
 
PPTX
Phan 1 mooc nen tang ket noi tri thuc (omt)
Nguyen Hung
 
PPTX
Chủ đề 1.tổng quan về elearning
Shinji Huy
 
PPTX
Báo cáo chủ đề 1: Tổng quan về e-learning
Thi Thanh Thuan Tran
 
PPTX
Url (uniform resource locator)
Ben Lee
 
PPTX
URL Presentation
vRudd
 
PDF
Url
bhylenia
 
PPT
Url Presentation
sanniii
 
PPT
Software engineering presentation
MJ Ferdous
 
PDF
An introduction to software engineering
Carlos Gavidia-Calderon
 
PPT
Software Engineering ppt
shruths2890
 
PDF
Annual Report - Mr. Pravin Ujjain
abciindia
 
PDF
豊橋の看板屋さんのパネル看板事例集
illumi kanban
 
PPTX
Presentation constructing an information panel
doogstone
 
PDF
Teaching manual of surumi. k
Sano Anil
 
6 quan ly-tien_trinh
vantinhkhuc
 
4 quan ly-nguoi_dung
vantinhkhuc
 
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...
Vu Hung Nguyen
 
Phan 1 mooc nen tang ket noi tri thuc (omt)
Nguyen Hung
 
Chủ đề 1.tổng quan về elearning
Shinji Huy
 
Báo cáo chủ đề 1: Tổng quan về e-learning
Thi Thanh Thuan Tran
 
Url (uniform resource locator)
Ben Lee
 
URL Presentation
vRudd
 
Url Presentation
sanniii
 
Software engineering presentation
MJ Ferdous
 
An introduction to software engineering
Carlos Gavidia-Calderon
 
Software Engineering ppt
shruths2890
 
Annual Report - Mr. Pravin Ujjain
abciindia
 
豊橋の看板屋さんのパネル看板事例集
illumi kanban
 
Presentation constructing an information panel
doogstone
 
Teaching manual of surumi. k
Sano Anil
 
Ad

Similar to Url programming (20)

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

More from vantinhkhuc (20)

PDF
Servlet sessions
vantinhkhuc
 
PDF
Security overview
vantinhkhuc
 
PDF
Rmi
vantinhkhuc
 
PDF
Md5
vantinhkhuc
 
PDF
Lecture17
vantinhkhuc
 
PDF
Lecture11 b
vantinhkhuc
 
PDF
Lecture10
vantinhkhuc
 
PDF
Lecture9
vantinhkhuc
 
PDF
Lecture6
vantinhkhuc
 
PDF
Jsse
vantinhkhuc
 
PDF
Jsf intro
vantinhkhuc
 
PDF
Jsp examples
vantinhkhuc
 
PDF
Jpa
vantinhkhuc
 
PDF
Ejb examples
vantinhkhuc
 
PDF
Corba
vantinhkhuc
 
PDF
Ajax
vantinhkhuc
 
PDF
Ejb intro
vantinhkhuc
 
PPT
Chc6b0c6a1ng 12
vantinhkhuc
 
PPT
Ch06
vantinhkhuc
 
PDF
Ajas11 alok
vantinhkhuc
 
Servlet sessions
vantinhkhuc
 
Security overview
vantinhkhuc
 
Lecture17
vantinhkhuc
 
Lecture11 b
vantinhkhuc
 
Lecture10
vantinhkhuc
 
Lecture9
vantinhkhuc
 
Lecture6
vantinhkhuc
 
Jsf intro
vantinhkhuc
 
Jsp examples
vantinhkhuc
 
Ejb examples
vantinhkhuc
 
Ejb intro
vantinhkhuc
 
Chc6b0c6a1ng 12
vantinhkhuc
 
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.