整理代码能够直接运行的示例:
1、抓取IP138上面的IP地理位置
/**
* @see 实现编码乱码问题
* */
public String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"gbk"));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
/**
* @author Administrator
* @return ip对应的城市名称
* */
public void getCityByIp() {
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost("" , 80, "http");
PostMethod post = new PostMethod( "/ips.asp" );
NameValuePair simcard = new NameValuePair( "ip" , this.ipString);
post.setRequestBody( new NameValuePair[] { simcard});
try {
client.executeMethod(post);
InputStream iStream = post.getResponseBodyAsStream();
String contentString = convertStreamToString(iStream);
Pattern p = Pattern.compile("来自.*
");//正则匹配出来
Matcher m = p.matcher(contentString);
while(m.find()) {
String content = m.group();
System.out.println("Match:" + content.replaceAll("?[^>]+>",""));
}
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
能够实现输入IP地址返回此IP所在的地理位置出来!
阅读(1051) | 评论(0) | 转发(0) |