读书人

依据IP获取地域信息

发布时间: 2012-12-19 14:13:14 作者: rapoo

根据IP获取地域信息

import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;public class IPBean {private String ip;public void setIp(String ip) {this.ip = ip;}public String getAddrByIP() {StringBuffer result = new StringBuffer();try {URL url = new URL("http://whois.pconline.com.cn/ip.jsp?ip=" + ip);HttpURLConnection connect = (HttpURLConnection) url.openConnection();InputStream is = connect.getInputStream();ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buff = new byte[256];int rc = 0;while ((rc = is.read(buff, 0, 256)) > 0) {outStream.write(buff, 0, rc);}byte[] b = outStream.toByteArray();// 关闭outStream.close();is.close();connect.disconnect();// 因为提供服务的网站使用GB2312编码,所以转化为字符串时也是GB2312,否则是乱码。字符集问题花了整整一天的时间,才解决,原因是对java的String理解不够透彻String aa = new String(b, "gb2312");result.append(aa);} catch (Exception e) {e.printStackTrace();result = null;}return result.toString();}}

import java.util.Scanner;import net.ip.bean.IPBean;public class IPUtil {public static void main(String[] args) {Scanner sc = new Scanner(System.in);try {String ip = sc.nextLine();IPBean bean = new IPBean();bean.setIp(ip);String result = bean.getAddrByIP();System.out.println(result);} catch (Exception ex) {System.err.println(ex.toString());}}}

读书人网 >编程

热点推荐