java 獲取真實ip和根據ip獲取ip所在地區


附上代碼:

 import com.alibaba.fastjson.JSON;
 import javax.servlet.http.HttpServletRequest;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.*;

public class AddrGetTest{

/**
 * 獲取真實ip地址
 *
 * @param request
 * @return
 */
public static String getIp(HttpServletRequest request) {
    String ipAddress = request.getHeader("x-forwarded-for");
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getHeader("Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getHeader("WL-Proxy-Client-IP");
    }
    if (StringUtils.isBlank(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getRemoteAddr();
        if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
            //根據網卡取本機配置的IP
            InetAddress inet = null;
            try {
                inet = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            ipAddress = inet.getHostAddress();
        }
    }
    //對於通過多個代理的情況,第一個IP為客戶端真實IP,多個IP按照','分割
    if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
        if (ipAddress.indexOf(",") > 0) {
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
        }
    }
    return ipAddress;
}
/**
 * 手機版獲取所有二級科目
 *
 * @des 根據三級科目和說明獲取所有二級科目
 * @version v1
 */
@GetMapping("v1/ips")
public Result listSecond(HttpServletRequest request) throws ActException {
    String addr = "";
    String ip = getIp(request);
    try {
        String str = getJsonContent("http://ip.taobao.com/service/getIpInfo.php?ip="+ip );
        System.out.println(str);
        String ss = JSON.toJSONString(str);
        AddressResult result = JSON.parseObject(str, AddressResult.class);
  //            System.out.println(ss);
  //            System.out.println(JSON.toJSONString(result));
        if ("0".equals(result.getCode())) {
            Address ad = JSON.parseObject(result.getData(), Address.class);
            addr = ad.getCountry() + "/" + ad.getArea() + "/" + ad.getRegion() + "/" + ad.getCity() + " " + ad.getIsp();
        } else {
            addr = "IP地址有誤";
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new ActException( "獲取IP地址異常:" + e.getMessage());
    }


    return ActResult.initialize(addr);

}



public static String getJsonContent(String urlStr) {
    try {// 獲取HttpURLConnection連接對象
        URL url = new URL(urlStr);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        // 設置連接屬性
        httpConn.setConnectTimeout(3000);
        httpConn.setDoInput(true);
        httpConn.setRequestMethod("GET");
        // 獲取相應碼
        int respCode = httpConn.getResponseCode();
        if (respCode == 200) {
            return ConvertStream2Json(httpConn.getInputStream());
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}

private static String ConvertStream2Json(InputStream inputStream) {
    String jsonStr = "";
    // ByteArrayOutputStream相當於內存輸出流
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;
    // 將輸入流轉移到內存輸出流中
    try {
        while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
            out.write(buffer, 0, len);
        }
        // 將內存流轉換為字符串
        jsonStr = new String(out.toByteArray());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return jsonStr;
}
    }


public class Address {
     private String country;
     private String area;
     private String region;
     private String city;
     private String isp;
     private Address(){

}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String getRegion() {
    return region;
}

public void setRegion(String region) {
    this.region = region;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getIsp() {
    return isp;
}

public void setIsp(String isp) {
    this.isp = isp;
}

public String getArea() {
    return area;
}

public void setArea(String area) {
    this.area = area;
}
  }


public class AddressResult {
  private String code;
  private String data;

  public String getCode() {
    return code;
 }

public void setCode(String code) {
    this.code = code;
}

public String getData() {
    return data;
}

public void setData(String data) {
    this.data = data;
}
  }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM