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
PDF
Ajax chap 2.-part 1
PDF
Ajax chap 3
PPT
ODP
Creating a Java EE 7 Websocket Chat Application
PDF
Web II - 02 - How ASP.NET Works
PDF
Introduction to Ajax programming
PDF
async/await in Swift
Servlets intro
Ajax chap 2.-part 1
Ajax chap 3
Creating a Java EE 7 Websocket Chat Application
Web II - 02 - How ASP.NET Works
Introduction to Ajax programming
async/await in Swift

What's hot (20)

PPTX
Test and profile your Windows Phone 8 App
PPTX
Windows 8 metro applications
PDF
Advanced #2 networking
PDF
Data models in Angular 1 & 2
PDF
Chapter 27 Networking - Deitel & Deitel
PDF
The Big Picture and How to Get Started
PDF
Testdrevet javautvikling på objektorienterte skinner
PPTX
Bare-knuckle web development
PPTX
Introduction to ASP.Net Viewstate
PPTX
Intro to Parse
PDF
Android - Saving data
DOCX
Sec.1 กล ม 1 เร__องการสร_างแบบฟอร_มและการส_งค_าต_วแปร
PPT
W3 C11
PDF
Android ui layouts ,cntls,webservices examples codes
PPTX
Yogesh kumar kushwah represent’s
PDF
Remote code-with-expression-language-injection
PDF
PDF
RicoAjaxEngine
PPT
Simple Data Binding
PPTX
What's Parse
Test and profile your Windows Phone 8 App
Windows 8 metro applications
Advanced #2 networking
Data models in Angular 1 & 2
Chapter 27 Networking - Deitel & Deitel
The Big Picture and How to Get Started
Testdrevet javautvikling på objektorienterte skinner
Bare-knuckle web development
Introduction to ASP.Net Viewstate
Intro to Parse
Android - Saving data
Sec.1 กล ม 1 เร__องการสร_างแบบฟอร_มและการส_งค_าต_วแปร
W3 C11
Android ui layouts ,cntls,webservices examples codes
Yogesh kumar kushwah represent’s
Remote code-with-expression-language-injection
RicoAjaxEngine
Simple Data Binding
What's Parse
Ad

Viewers also liked (20)

PDF
6 quan ly-tien_trinh
PDF
4 quan ly-nguoi_dung
PDF
PDF
PPTX
Chude01 nhom10_TỔNG QUAN VỀ ELEARNING_VERSION2
PDF
Mhst- 2013 14 Nghiên cứu triển khai hệ thống MOOC cho Việt Nam dựa trên...
PPTX
Phan 1 mooc nen tang ket noi tri thuc (omt)
PPTX
Chủ đề 1.tổng quan về elearning
PPTX
Báo cáo chủ đề 1: Tổng quan về e-learning
PPTX
Url (uniform resource locator)
PPTX
URL Presentation
PDF
PPT
Url Presentation
PPT
Software engineering presentation
PDF
An introduction to software engineering
PPT
Software Engineering ppt
PDF
Annual Report - Mr. Pravin Ujjain
PDF
豊橋の看板屋さんのパネル看板事例集
PPTX
Presentation constructing an information panel
PDF
Teaching manual of surumi. k
6 quan ly-tien_trinh
4 quan ly-nguoi_dung
Chude01 nhom10_TỔNG QUAN VỀ ELEARNING_VERSION2
Mhst- 2013 14 Nghiên cứu triển khai hệ thống MOOC cho Việt Nam dựa trên...
Phan 1 mooc nen tang ket noi tri thuc (omt)
Chủ đề 1.tổng quan về elearning
Báo cáo chủ đề 1: Tổng quan về e-learning
Url (uniform resource locator)
URL Presentation
Url Presentation
Software engineering presentation
An introduction to software engineering
Software Engineering ppt
Annual Report - Mr. Pravin Ujjain
豊橋の看板屋さんのパネル看板事例集
Presentation constructing an information panel
Teaching manual of surumi. k
Ad

Similar to Url programming (20)

PDF
21servers And Applets
PPTX
Client-Server
PPTX
Rpi python web
PPTX
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
PPTX
Asp.net server control
PPTX
Ajax
DOC
T2
PDF
URL Class in Java.pdf
PDF
Web Development with NodeJS
PPT
Html intake 38 lect1
PPTX
Swift LA Meetup at eHarmony- What's New in Swift 2.0
PPTX
Python Code Camp for Professionals 4/4
PPTX
Web Technologies - forms and actions
KEY
Java web programming
DOCX
Copy of cgi
PDF
Automating Cloud Operations: Everything You Wanted to Know about cURL and REST
PDF
servlets
PPTX
Introduction to the SharePoint Client Object Model and REST API
PPTX
Controller Request and Response in Odoo18
21servers And Applets
Client-Server
Rpi python web
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Asp.net server control
Ajax
T2
URL Class in Java.pdf
Web Development with NodeJS
Html intake 38 lect1
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Python Code Camp for Professionals 4/4
Web Technologies - forms and actions
Java web programming
Copy of cgi
Automating Cloud Operations: Everything You Wanted to Know about cURL and REST
servlets
Introduction to the SharePoint Client Object Model and REST API
Controller Request and Response in Odoo18

More from vantinhkhuc (20)

PDF
Servlet sessions
PDF
Security overview
PDF
PDF
PDF
Lecture17
PDF
Lecture11 b
PDF
Lecture10
PDF
Lecture9
PDF
Lecture6
PDF
PDF
Jsf intro
PDF
Jsp examples
PDF
PDF
Ejb examples
PDF
PDF
PDF
Ejb intro
PPT
Chc6b0c6a1ng 12
PPT
PDF
Ajas11 alok
Servlet sessions
Security overview
Lecture17
Lecture11 b
Lecture10
Lecture9
Lecture6
Jsf intro
Jsp examples
Ejb examples
Ejb intro
Chc6b0c6a1ng 12
Ajas11 alok

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.