java 物理地址_java查询IP物理地址
根据访问的IP得到具体的IP物理地址,在这里要采用HttpURLConnection向http://www.ip.cn发送请求,之后由该网站做具体的IP分析,将结果以字符串的形式返回给我们,代码如下:
public class Ipservice {
//连接对象
/**
* 根据url连接某地址,并返回返回码.
* 返回码说明:
* 0~200为正常情况,其中200为OK
* @param urlStr 需连接的url字符串
*/
public void connect(HttpURLConnection conn) throws Exception {
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
}
/**
* 发送ip
* @param ip地址
*/
private void send(String ip,HttpURLConnection conn) throws Exception {
OutputStreamWriter sw=new OutputStreamWriter(new BufferedOutputStream(conn.getOutputStream()));
sw.write(ip);
sw.flush();
sw.close();
}
/**
* 读取网页的内容.
* @return 返回ip所在地
*/
private String readContents(HttpURLConnection conn) throws Exception {
String ip_addr="";
int row=0;
BufferedReader in = null;
in = new BufferedReader(new InputStreamReader(conn
.getInputStream(),"gb2312"));
String inputLine;
while ((inputLine = in.readLine()) != null) {
row++;
//if(row==3 || row==4)
//ip_addr+=inputLine.replace("", "").replace("","")+",";
ip_addr+=inputLine;
ip_addr=ip_addr.substring(ip_addr.indexOf("来自:")+3);
}
return ip_addr;
}
/**
* 中断连接.
*/
private void disconnect(HttpURLConnection conn) {
conn.disconnect();
}
public String getIp(String ip){
String ip_addr="";
HttpURLConnection conn = null;
try{
// connect("http://www.ip138.com/ips.asp?");
URL url = new URL("http://www.ip.cn/getip.php?action=queryip&ip_url="+ip);
conn = (HttpURLConnection) url.openConnection();
connect(conn);
send("",conn);
ip_addr=readContents(conn);
}catch(Exception e){
ip_addr="webservice调用出现问题";
e.printStackTrace();
}finally{
if(conn!=null)
disconnect(conn);
}
return ip_addr;
}
}
分享到:


2010-06-23 18:46
浏览 1341
评论
1 楼
lufengdie
2010-08-02
借用下,嘿嘿··
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
