获取IP地址,并根据IP地址定位到位置

package com.example.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.Charset;

import net.sf.json.JSONObject;




public class IpAddressDemo {
	
	
	/**
	 * 本地IP地址
	 * @return
	 */
	public static void getLocalIP() {
		  
		InetAddress addr;
		try {
			addr = InetAddress.getLocalHost();
			System.out.println("Local HostAddress:  "+addr.getHostAddress()); String
			hostname = addr.getHostName();
			System.out.println("Local host name: "+hostname);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		
	}
	
	
	/*
	 * 获得本机公网ip
	 */
	public static String getIP() {
		String ip = "http://pv.sohu.com/cityjson?ie=utf-8";

		String inputLine = "";
		String read = "";
		try {
			URL url = new URL(ip);
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			while ((read = in.readLine()) != null) {
				inputLine += read;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		String[] split = inputLine.replace(";", "").split("=");
		JSONObject json = JSONObject.fromObject(split[1]);
		String ipstr = json.get("cip").toString();
		return ipstr;
	}
	
	/**
	 * 调用百度api返回ip地址的定位
	 * @return
	 * @throws IOException
	 */
	public static String getAddrName() throws IOException{
        //这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
        JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=oBbSaFZqmC0i1CNg8rYwaSkGlmdYHbAO&ip="+getIP());
        /* 获取到的json对象:
         *         {"address":"CN|河北|保定|None|UNICOM|0|0",
         *        "content":{"address_detail":{"province":"河北省","city":"保定市","street":"","district":"","street_number":"","city_code":307},
         *        "address":"河北省保定市","point":{"x":"12856963.35","y":"4678360.5"}},
         *        "status":0}
        */
        //这里我们可以输出json看一下具体格式
        System.out.println(json.toString());

        JSONObject content=json.getJSONObject("content");              //获取json对象里的content对象
        JSONObject addr_detail=content.getJSONObject("address_detail");//从content对象里获取address_detail
        String city=addr_detail.get("city").toString();                //获取市名,可以根据具体需求更改,如果需要获取省份的名字,可以把“city”改成“province”...
        return city;
    }

	
	
	public static JSONObject readJsonFromUrl(String url) throws IOException {
        InputStream is = null;
        try {
            is = new URL(url).openStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = JSONObject.fromObject(jsonText);  
            return json;
        } finally {
        	//关闭输入流
        	is.close();
        }
    }
	
	private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }
	
	
	public static void main(String[] args) throws IOException {
		System.out.println(getAddrName());
		System.out.println(getIP());
	}
	
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值