Java如何與Web伺服器連線?

2019-10-16 22:27:55

在Java程式設計中,如何與Web伺服器連線?

以下範例演示如何使用net.Socket類的sock.getInetAddress()方法與Web伺服器連線。

package com.yiibai;

import java.net.InetAddress;
import java.net.Socket;

public class Connected2Server {
    public static void main(String[] args) {
        try {
            InetAddress addr;
            Socket sock = new Socket("www.tw511.com", 80);
            addr = sock.getInetAddress();
            System.out.println("Connected to " + addr);
            sock.close();
        } catch (java.io.IOException e) {
            System.out.println("Can't connect to " + args[0]);
            System.out.println(e);
        }
    }
}

上述程式碼範例將產生以下結果 -

Connected to www.tw511.com/112.124.103.85