SlideShare una empresa de Scribd logo
1 de 9
Descargar para leer sin conexión
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.

Más contenido relacionado

La actualidad más candente

Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppMichele Capra
 
Windows 8 metro applications
Windows 8 metro applicationsWindows 8 metro applications
Windows 8 metro applicationsAlex Golesh
 
Advanced #2 networking
Advanced #2   networkingAdvanced #2   networking
Advanced #2 networkingVitali Pekelis
 
Data models in Angular 1 & 2
Data models in Angular 1 & 2Data models in Angular 1 & 2
Data models in Angular 1 & 2Adam Klein
 
Chapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & DeitelChapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & DeitelCSDeptSriKaliswariCo
 
The Big Picture and How to Get Started
The Big Picture and How to Get StartedThe Big Picture and How to Get Started
The Big Picture and How to Get Startedguest1af57e
 
Testdrevet javautvikling på objektorienterte skinner
Testdrevet javautvikling på objektorienterte skinnerTestdrevet javautvikling på objektorienterte skinner
Testdrevet javautvikling på objektorienterte skinnerTruls Jørgensen
 
Bare-knuckle web development
Bare-knuckle web developmentBare-knuckle web development
Bare-knuckle web developmentJohannes Brodwall
 
Sec.1 กล ม 1 เร__องการสร_างแบบฟอร_มและการส_งค_าต_วแปร
Sec.1 กล  ม 1 เร__องการสร_างแบบฟอร_มและการส_งค_าต_วแปรSec.1 กล  ม 1 เร__องการสร_างแบบฟอร_มและการส_งค_าต_วแปร
Sec.1 กล ม 1 เร__องการสร_างแบบฟอร_มและการส_งค_าต_วแปรBongza Naruk
 
Android ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAndroid ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAravindharamanan S
 
Yogesh kumar kushwah represent’s
Yogesh kumar kushwah represent’sYogesh kumar kushwah represent’s
Yogesh kumar kushwah represent’sYogesh Kushwah
 
Remote code-with-expression-language-injection
Remote code-with-expression-language-injectionRemote code-with-expression-language-injection
Remote code-with-expression-language-injectionMickey Jack
 

La actualidad más candente (20)

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

Destacado

6 quan ly-tien_trinh
6 quan ly-tien_trinh6 quan ly-tien_trinh
6 quan ly-tien_trinhvantinhkhuc
 
4 quan ly-nguoi_dung
4 quan ly-nguoi_dung4 quan ly-nguoi_dung
4 quan ly-nguoi_dungvantinhkhuc
 
Chude01 nhom10_TỔNG QUAN VỀ ELEARNING_VERSION2
Chude01 nhom10_TỔNG QUAN VỀ ELEARNING_VERSION2Chude01 nhom10_TỔNG QUAN VỀ ELEARNING_VERSION2
Chude01 nhom10_TỔNG QUAN VỀ ELEARNING_VERSION2Tuyen 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...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)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ề elearningChủ đề 1.tổng quan về elearning
Chủ đề 1.tổng quan về elearningShinji Huy
 
Báo cáo chủ đề 1: Tổng quan về e-learning
Báo cáo chủ đề 1: Tổng quan về e-learningBáo cáo chủ đề 1: Tổng quan về e-learning
Báo cáo chủ đề 1: Tổng quan về e-learningThi Thanh Thuan Tran
 
Url (uniform resource locator)
Url (uniform resource locator)Url (uniform resource locator)
Url (uniform resource locator)Ben Lee
 
URL Presentation
URL PresentationURL Presentation
URL PresentationvRudd
 
Url Presentation
Url PresentationUrl Presentation
Url Presentationsanniii
 
Software engineering presentation
Software engineering presentationSoftware engineering presentation
Software engineering presentationMJ Ferdous
 
Software Engineering ppt
Software Engineering pptSoftware Engineering ppt
Software Engineering pptshruths2890
 
Annual Report - Mr. Pravin Ujjain
Annual Report - Mr. Pravin UjjainAnnual Report - Mr. Pravin Ujjain
Annual Report - Mr. Pravin Ujjainabciindia
 
豊橋の看板屋さんのパネル看板事例集
豊橋の看板屋さんのパネル看板事例集豊橋の看板屋さんのパネル看板事例集
豊橋の看板屋さんのパネル看板事例集illumi kanban
 
Presentation constructing an information panel
Presentation   constructing an information panelPresentation   constructing an information panel
Presentation constructing an information paneldoogstone
 
Teaching manual of surumi. k
Teaching manual of surumi. kTeaching manual of surumi. k
Teaching manual of surumi. kSano Anil
 

Destacado (20)

6 quan ly-tien_trinh
6 quan ly-tien_trinh6 quan ly-tien_trinh
6 quan ly-tien_trinh
 
4 quan ly-nguoi_dung
4 quan ly-nguoi_dung4 quan ly-nguoi_dung
4 quan ly-nguoi_dung
 
Bai4
Bai4Bai4
Bai4
 
Bai 5
Bai 5Bai 5
Bai 5
 
Chude01 nhom10_TỔNG QUAN VỀ ELEARNING_VERSION2
Chude01 nhom10_TỔNG QUAN VỀ ELEARNING_VERSION2Chude01 nhom10_TỔNG QUAN VỀ ELEARNING_VERSION2
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...
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...
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)
Phan 1   mooc nen tang ket noi tri thuc (omt)Phan 1   mooc nen tang ket noi tri thuc (omt)
Phan 1 mooc nen tang ket noi tri thuc (omt)
 
Chủ đề 1.tổng quan về elearning
Chủ đề 1.tổng quan về elearningChủ đề 1.tổng quan về elearning
Chủ đề 1.tổng quan về elearning
 
Báo cáo chủ đề 1: Tổng quan về e-learning
Báo cáo chủ đề 1: Tổng quan về e-learningBáo cáo chủ đề 1: Tổng quan về e-learning
Báo cáo chủ đề 1: Tổng quan về e-learning
 
Url (uniform resource locator)
Url (uniform resource locator)Url (uniform resource locator)
Url (uniform resource locator)
 
URL Presentation
URL PresentationURL Presentation
URL Presentation
 
Url
UrlUrl
Url
 
Url Presentation
Url PresentationUrl Presentation
Url Presentation
 
Software engineering presentation
Software engineering presentationSoftware engineering presentation
Software engineering presentation
 
An introduction to software engineering
An introduction to software engineeringAn introduction to software engineering
An introduction to software engineering
 
Software Engineering ppt
Software Engineering pptSoftware Engineering ppt
Software Engineering ppt
 
Annual Report - Mr. Pravin Ujjain
Annual Report - Mr. Pravin UjjainAnnual Report - Mr. Pravin Ujjain
Annual Report - Mr. Pravin Ujjain
 
豊橋の看板屋さんのパネル看板事例集
豊橋の看板屋さんのパネル看板事例集豊橋の看板屋さんのパネル看板事例集
豊橋の看板屋さんのパネル看板事例集
 
Presentation constructing an information panel
Presentation   constructing an information panelPresentation   constructing an information panel
Presentation constructing an information panel
 
Teaching manual of surumi. k
Teaching manual of surumi. kTeaching manual of surumi. k
Teaching manual of surumi. k
 

Similar a Url programming

21servers And Applets
21servers And Applets21servers And Applets
21servers And AppletsAdil Jafri
 
Rpi python web
Rpi python webRpi python web
Rpi python websewoo lee
 
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...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 controlAsp.net  server control
Asp.net server controlSireesh K
 
Web Development with NodeJS
Web Development with NodeJSWeb Development with NodeJS
Web Development with NodeJSRiza Fahmi
 
Html intake 38 lect1
Html intake 38 lect1Html intake 38 lect1
Html intake 38 lect1ghkadous
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Claire Townend Gee
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4DEVCON
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren Zomorodian
 
Java web programming
Java web programmingJava web programming
Java web programmingChing 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 RESTAutomating Cloud Operations: Everything You Wanted to Know about cURL and REST
Automating Cloud Operations: Everything You Wanted to Know about cURL and RESTRevelation Technologies
 
Introduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIIntroduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIRob Windsor
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSCosmin Mereuta
 

Similar a Url programming (20)

21servers And Applets
21servers And Applets21servers And Applets
21servers And Applets
 
Cgi
CgiCgi
Cgi
 
Client-Server
Client-ServerClient-Server
Client-Server
 
Rpi python web
Rpi python webRpi python web
Rpi python web
 
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
 
Asp.net server control
Asp.net  server controlAsp.net  server control
Asp.net server control
 
Ajax
AjaxAjax
Ajax
 
T2
T2T2
T2
 
URL Class in Java.pdf
URL Class in Java.pdfURL Class in Java.pdf
URL Class in Java.pdf
 
Web Development with NodeJS
Web Development with NodeJSWeb Development with NodeJS
Web Development with NodeJS
 
Html intake 38 lect1
Html intake 38 lect1Html intake 38 lect1
Html intake 38 lect1
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
Java web programming
Java web programmingJava web programming
Java web programming
 
Copy of cgi
Copy of cgiCopy of cgi
Copy of cgi
 
Automating Cloud Operations: Everything You Wanted to Know about cURL and REST
Automating Cloud Operations: Everything You Wanted to Know about cURL and RESTAutomating Cloud Operations: Everything You Wanted to Know about cURL and REST
Automating Cloud Operations: Everything You Wanted to Know about cURL and REST
 
servlets
servletsservlets
servlets
 
Introduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIIntroduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST API
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
 

Más de vantinhkhuc (20)

Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
 
Security overview
Security overviewSecurity overview
Security overview
 
Rmi
RmiRmi
Rmi
 
Md5
Md5Md5
Md5
 
Lecture17
Lecture17Lecture17
Lecture17
 
Lecture11 b
Lecture11 bLecture11 b
Lecture11 b
 
Lecture10
Lecture10Lecture10
Lecture10
 
Lecture9
Lecture9Lecture9
Lecture9
 
Lecture6
Lecture6Lecture6
Lecture6
 
Jsse
JsseJsse
Jsse
 
Jsf intro
Jsf introJsf intro
Jsf intro
 
Jsp examples
Jsp examplesJsp examples
Jsp examples
 
Jpa
JpaJpa
Jpa
 
Ejb examples
Ejb examplesEjb examples
Ejb examples
 
Corba
CorbaCorba
Corba
 
Ajax
AjaxAjax
Ajax
 
Ejb intro
Ejb introEjb intro
Ejb intro
 
Chc6b0c6a1ng 12
Chc6b0c6a1ng 12Chc6b0c6a1ng 12
Chc6b0c6a1ng 12
 
Ch06
Ch06Ch06
Ch06
 
Ajas11 alok
Ajas11 alokAjas11 alok
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.