Top Banner

of 25

236369 Networking Part II

Apr 06, 2018

Download

Documents

anumano
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/2/2019 236369 Networking Part II

    1/25

    1

    Java Networking

    CS 236369, Spring 2010

  • 8/2/2019 236369 Networking Part II

    2/25

    2

    Todays Menu

    Networking Basics

    TCP, UDP, Ports, DNS, Client-Server Model

    TCP/IP in Java

    Sockets

    URL

    The java classes: URL, URLEncoder,

    URLConnection, HTTPURLConnection

    Datagrams

    Networking in JDBC

  • 8/2/2019 236369 Networking Part II

    3/25

    3

    URL - Uniform Resource Locator

    Protocol

    Host

    Name

    Port

    Number

    Path &

    File

    Name

    Reference

    URL is a reference (an address) to a resourceon the Internet. A resource can be a file, a database query and more.

    URLs are just a subsetofthe more general conceptofUniformResource Identifiers (URIs) which are meanttodescribe all

    points in the information space

    http://www.javapassion.com:80/javaintro/index.html#Networking_API

  • 8/2/2019 236369 Networking Part II

    4/25

    4

    Class URL

    Class URL represents a Uniform Resource

    Locator, a pointerto a "resource" on the World

    Wide Web.

    Wedistinguish between: Absolute URL - contains all ofthe information

    necessary to reach the resource.

    Relative URL - contains only enough information to

    reach the resource relativeto (or in the contextof)another URL.

  • 8/2/2019 236369 Networking Part II

    5/25

    5

    Class URL Cont.

    Constructing URLs: URL w3c1 = new URL("http://www.w3.org/TR/");

    URL w3c2 = new

    URL("http","www.w3.org",80,"TR/"); URL w3c3 = new URL(w3c2, "xhtml1/");

    Ifthe string is not an absolute URL, then it is

    considered relativetothe URL

    More constructors can befound in theURLAPI

  • 8/2/2019 236369 Networking Part II

    6/25

    6

    URL Encoding

    URL Encoding is the process ofconverting string

    into valid URL format.

    V

    alid

    URLfo

    rmat

    me

    anst

    hat

    t

    he

    URL co

    nt

    ainsonly what is termed "alpha | digit | safe | extra |

    escape" characters.

    You can read more aboutthewhat andthewhys ofthese

    terms on the World Wide Web Consortiumsite: http://www.w3.org/Addressing/URL/url-spec.html

    URL Encoding Reference

  • 8/2/2019 236369 Networking Part II

    7/25

    7

    URL EncodingCont.

    Among the rest, URL encoding is performedtoconvertdata passed via html forms, because suchdata may contain special character, such as "/",".", "#", and soon, which couldeither:

    Have special meanings

    Is not a valid characterfor an URL

    For instance, the "#" character needs to beencoded because it has a special meaning ofthatofan html anchor. The character alsoneeds to beencoded because is not allowedon avalid URL format.

  • 8/2/2019 236369 Networking Part II

    8/25

    8

    URL EncodingCont.

    Example: The URL encoding ofThis is a

    simple & short test is

    This+is+a+simple+%26+short+test

    Notethat becausethe character is very

    commonly used, a special code ( the "+" sign) hasbeen reserved as its URL encoding

  • 8/2/2019 236369 Networking Part II

    9/25

    9

    URL addresses with Special characters

    Some URL addresses also contain these special characters, for

    examplethe space character.

    Likethis: http://foo.com/helloworld/

    To maketheses characters legal they needto beencoded before

    passing them tothe URL constructor.URL url = new URL("http://foo.com/hello%20world");

    One class that can help us with this is theURI class :

    URI uri = new URI("http", "foo.com", "/hello world/", "");

    URL url = uri.toURL();

    Anotherone is theURLEncoder class

  • 8/2/2019 236369 Networking Part II

    10/25

    10

    URLEncoder

    Contains a utility methodencodefor converting a string

    into an encodedformat (used in URLs)

    To convert a string, each character is examined in turn:

    Space is converted into a plus sign +

    a-z, A-Z, 0-9, ., -, * and_remain the same.

    The bytes ofall special characters are replaced by hexadecimal

    numbers, precededwith %

    Todecode an encoded string, use decode() ofthe classURLDecoder

    The URLEncoder API.

  • 8/2/2019 236369 Networking Part II

    11/25

    11

    MalformedURLException

    URL constructors throws aMalformedURLException ifthe arguments to

    the constructor referto a null orunknown protocol.

    Typically, youwantto catch and handlethisexception by embedding your URL constructor

    statements in a try/catch pair, likethis:

    try

    { URL myURL = new URL(. . .) }

    catch(MalformedURLException e)

    { ... // exception handler code here ... }

  • 8/2/2019 236369 Networking Part II

    12/25

    12

    ImFeelingLucky Example Thefollowing program sends a requesttothe Google server andextracts the result.

    Google search engine accepts GET requests ofa specific format. Its reply alwayscontain a Location header line ifthe search is successful.

  • 8/2/2019 236369 Networking Part II

    13/25

    13

    ImFeelingLucky Example Cont.

    Finally wouldbethe right

    place

  • 8/2/2019 236369 Networking Part II

    14/25

    14

    UTF-8 In Short Unicode

    is a comp

    uting in

    dustry s

    tan

    dard

    allow

    ing comp

    uters

    toconsistently represent and manipulatetextexpressed in mostofthe

    world's writing systems.

    Unicode provides a unique numberforevery character,no matter what the platform,no matter what the program,

    no matter what the language. UTF-8 (8-bit UCS/Unicode Transformation Format) is a variable-

    length characterencoding for Unicode. It is ableto represent anycharacter in the Unicode standard, yet is backwards compatiblewithASCII. Forthese reasons, it is steadily becoming the preferredencoding fore-mail, web pages, andother places where characters arestoredor streamed.

    UTF-8 encodes each character in onetofouroctets (8-bit bytes), withthe 1-byteencoding usedonly forthe 128 US-ASCII characters.

  • 8/2/2019 236369 Networking Part II

    15/25

    15

    Parsing a URL

    Thefollowing methods ofURL can beusedfor

    parsing URLs:

    getProtocol(), getHost(),

    getPort(), getPath(), getFile(),

    getQuery(), getRef()

  • 8/2/2019 236369 Networking Part II

    16/25

    16

    import java.net.*;

    import java.io.*;

    public class ParseURL {

    public static voidmain(String[] args) throws Exception {URL aURL = new URL("http://java.sun.com:80/docs/books/tutorial"

    + "/index.html?name=networking#DOWNLOADING");

    System.out.println("protocol = " + aURL.getProtocol());

    System.out.println("authority = " + aURL.getAuthority());

    System.out.println("host = " + aURL.getHost());

    System.out.println("port = " + aURL.getPort());

    System.out.println("path = " + aURL.getPath());

    System.out.println("query = " + aURL.getQuery());System.out.println("filename = " + aURL.getFile());

    System.out.println("ref = " + aURL.getRef());

    }

    }

    The Outputprotocol = http

    authority = java.sun.com:80

    host = java.sun.com

    port = 80

    path = /docs/books/tutorial/index.html

    query = name=networking

    filename = /docs/books/tutorial/index.html?name=networking

    ref = DOWNLOADING

  • 8/2/2019 236369 Networking Part II

    17/25

    17

    URLConnection

    Represent a communications link between the application and aURL. Instances ofthis class can beused both to readfrom andtowritetothe resource referenced by the URL.

    Creating a connection to a URL:

    The connection object is created by invoking theopenConnectionmethodon a URL. Ifthe protocol ofthe URL is HTTP, the returned

    object is ofclass HttpURLConnection.

    The setup parameters and general request properties are manipulated.

    The actual connection tothe remoteobject is made, using theconnectmethod.

    The remoteobject becomes available. The headerfields andthe

    contents ofthe remoteobject can be accessed. SeetheURLConnection class API for more information

  • 8/2/2019 236369 Networking Part II

    18/25

  • 8/2/2019 236369 Networking Part II

    19/25

    19

    URLConnection Example

    Whatwill happened ifyouwill try torun this codewhile not

    connectedtotheweb?

  • 8/2/2019 236369 Networking Part II

    20/25

  • 8/2/2019 236369 Networking Part II

    21/25

    21

    Class HttpURLConnection

    A URLConnection with supportfor HTTP-

    specific features.

    responseMessage field

    getRequestMethod()

    usingProxy()

    There is no needto create HTTP parsers

    The HttpURLConnection API

  • 8/2/2019 236369 Networking Part II

    22/25

    22

    Datagrams

    A datagram is an independent, self-contained

    message sentoverthe networkwhose arrival,

    arrival time, and content are not guaranteed.

    Thejava.netpackage contains three classes to

    help youwrite Java programs thatusedatagrams

    to send and receive packets overthe network:

    DatagramSocket, DatagramPacket, andMulticastSocket

  • 8/2/2019 236369 Networking Part II

    23/25

    23

    Networking in JDBC

    You actually already met Sockets.

  • 8/2/2019 236369 Networking Part II

    24/25

    24

    Can be anywhere! (not

    necessarily localhost

    usually remote)

  • 8/2/2019 236369 Networking Part II

    25/25

    25

    Resources

    The Java Tutorials Sun Microsystems

    An Introduction to XML and Web Technologies /

    Anders Mller andMichael I. Schwartzbach

    course literature

    http://www.cs.huji.ac.il/~dbi

    Wikipedia

    http://www.permadi.com/tutorial/urlEncoding/