Java網路編程之InetAddress和URL

來源:互聯網
上載者:User

標籤:ati   local   asn   mit   資料報   ddr   引用   簡介   ack   

在Java中提供了專門的網路開發程式包---java.net,java的網路編程提供了兩種通訊協定:TCP(傳輸控制通訊協定)和UDP(資料報協議)。

一.IP(Internet Protocol) 與InetAddress類

1.IP簡介

互連網上的每一台電腦都有一個唯一表示自己的標識,即IP地址。

IP地址=網路地址+主機地址

2.InetAddress

該類主要表示IP地址,有兩個子類:Inet4Address、Inet6Address,前者表示IPV4,後者表示IPV6。

InetAddress類的常用方法有:

類型 方法 描述
static InetAddress getByName(Stringhost) 在給定主機名稱的情況下確定主機的 IP 位址。
static InetAddress

getLocalHost()

返回本地主機。
String getHostName() 擷取此 IP 位址的主機名稱。
boolean isReachable(int timeout) 測試是否可以達到該地址。
測試InetAddress類:
package org.demo.net;import java.net.InetAddress;/** * 測試InetAddress類 * @author oushine */public class InetAddressDemo {    public static void main(String[] args) {        try {            //聲明並得到本地InetAddress對象            InetAddress iAddress1=InetAddress.getLocalHost();            //聲明並得到遠程InetAddress對象            InetAddress iAddress2=InetAddress.getByName("www.baidu.com");            //獲得本地IP地址            System.out.println("本機IP地址為:"+iAddress1.getHostAddress());            //獲得遠程IP地址            System.out.println("百度的IP地址是:"+iAddress2.getHostAddress());            System.out.println("本機是否可達:"+iAddress1.isReachable(3000));        } catch (Exception e) {            e.printStackTrace();        }    }}

結果:

 

二.URL與URLConnection

1.URL

URL(Uniform Resource Locator)是統一資源定位器,可以直接使用此類找到互連網上的資源(比如一個網頁)。

URL類常用方法:

類型 方法 描述
構造方法

URL(String spec)

根據 String 表示形式建立 URL 對象。
構造方法 URL(String protocol, String host, int port, String file) 根據指定 protocolhostport 號和 file 建立 URL 對象。
URLConnection openConnection() 返回一個 URLConnection 對象,它表示到 URL 所引用的遠程對象的串連。
InputStream

openStream()

開啟到此 URL 的串連並返回一個用於從該串連讀入的 InputStream
使用URL讀取內容:
package org.demo.net;import java.io.InputStream;import java.net.MalformedURLException;import java.net.URL;import java.util.Scanner;public class UrlDemo {    public static void main(String[] args) {        URL url;        try {            //指定操作的URL            url = new URL("http","www.baidu.com",80,"/index.html");            //開啟輸入資料流,讀取URL內容            InputStream inputStream=url.openStream();            Scanner scan=new Scanner(inputStream);            //設定讀取分隔字元            scan.useDelimiter("\n");            while(scan.hasNext()){                //輸出內容                System.out.println(scan.next());            }        } catch (Exception e) {            e.printStackTrace();        }    }}

結果:

顯示出來的是HTML代碼。

2.URLConnection

URLConnection是封裝訪問遠程網路資源一般方法的類,通過它可以建立與遠程伺服器的串連,檢查遠端資源的一些屬性。

常用方法:

類型 方法 描述
int

getContentLength()

返回 content-length 頭欄位的值。
String

getContentType()

返回 content-type 頭欄位的值。
InputStream

getInputStream()

返回從此開啟的串連讀取的輸入資料流。

URLConnection對象可以通過URL類的openConnection()方法取得。

取得URL的基本資料:
package org.demo.net;import java.net.URL;import java.net.URLConnection;public class URLConnectionDemo {    public static void main(String[] args) {        try {            URL url=new URL("http://www.baidu.com");            //建立串連            URLConnection urlConn=url.openConnection();            System.out.println("內容大小:"+urlConn.getContentLength());            System.out.println("內容類型:"+urlConn.getContentType());        } catch (Exception e) {            e.printStackTrace();        }    }}
運行結果:

 
 

三.URLEncoder與URLDecoder

在java中如果需要完成編碼和解碼操作就要使用URLEncoder和URLDecoder兩個類。

URLEncoder類的方法:

類型 方法 描述
static String encode(String s, String enc) 使用指定的編碼機制將字串轉換為 application/x-www-form-urlencoded 格式。

URLDecoder類的方法:

類型 方法 描述
static String decode(String s, String enc) 使用指定的編碼機制對 application/x-www-form-urlencoded 字串解碼。
編碼及解碼操作:
package org.demo.net;import java.net.URLDecoder;import java.net.URLEncoder;public class CodeDemo {    public static void main(String[] args) {        String keyWord="oushine 陽";        try {            String enCode=URLEncoder.encode(keyWord, "UTF-8");            System.out.println("編碼之後:"+enCode);            String deCode=URLDecoder.decode(enCode, "UTF-8");            System.out.println("解碼之後:"+deCode);        } catch (Exception e) {            e.printStackTrace();        }            }}

運行結果:

 

轉自:https://www.cnblogs.com/yzl-i/p/4442892.html#top

Java網路編程之InetAddress和URL

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.