集册 Java实例教程 通过web服务获取当前IP地址

通过web服务获取当前IP地址

欢马劈雪     最近更新时间:2020-01-02 10:19:05

394
通过web服务获取当前IP地址


import java.io.BufferedReader;

import java.io.IOException;
/*
时代Java公众号 - nowjava.com 提供
*/

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;


public class Main{

    public static void main(String[] argv) throws Exception{

        System.out.println(getCurrentIPAddress());

    }

    private static final String PUBLIC_ADDRESS_URL = "http://ipinfo.io/ip";

    private static String ipAddress;

    public static String getCurrentIPAddress()

            throws CantGetCurrentIPAddressException {


        if (ipAddress != null)

            return ipAddress;


        HttpURLConnection conn = null;/*n o w j a   v  a . c o m - 时  代  Java 提供*/

        try {


            conn = (HttpURLConnection) new URL(PUBLIC_ADDRESS_URL)

                    .openConnection();

            BufferedReader reader = new BufferedReader(

                    new InputStreamReader(conn.getInputStream()));

            String response = reader.readLine();


            if (conn.getResponseCode() == 200) {

                ipAddress = response.trim();

                return ipAddress;

            } else

                throw new CantGetCurrentIPAddressException(null, "",

                        "We couldn't find out the ip address.");


        } catch (IOException ioException) {


            throw 
展开阅读全文