package cn.com.jsoft.common.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 版权所有 All Rights Reserved
*
* @author Irving
* @description 获得该IP对应的城市
* @date 2013年6月28日13:48:38
* @version 1.0.0
* @email zhouyongtao@outlook.com
*/
public class HttpIpAddress {
/**
* 支持普通HTTP请求 WCF WEBSERVICE
*
* @param url
* @param xml
* WCF XML参数
* @param method
* @param contentType
* @param timeOut
* @return
*/
public static String HttpProxy(String url, String xml, String method, String contentType, String timeOut) {
OutputStream os = null;
HttpURLConnection conn = null;
BufferedReader reader = null;
StringBuffer sb = null;
try {
if (StringUtils.isEmpty(method)) {
method = "GET";
}
if (StringUtils.isEmpty(contentType)) {
contentType = "application/x-www-form-urlencoded";// "application/x-java-serialized-object"
}
if (StringUtils.isEmpty(timeOut)) {
timeOut = "5000";
}
URL _url = new URL(url);
conn = (HttpURLConnection) _url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod(method);
conn.setRequestProperty("Content-type", contentType);
conn.setConnectTimeout(Integer.parseInt(timeOut));
// conn.setRequestProperty("Accept-Language","zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
// conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
// conn.setRequestProperty("Content-Type", "text/xml;charset=GBK");
// 请求参数
if (!StringUtils.isEmpty(xml)) {
os = conn.getOutputStream();
os.write(xml.getBytes());
os.flush();
}
// 返回值
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
conn.connect();
// InputStreamReader inReader = new InputStreamReader(is,
// "UTF-8");
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
sb = new StringBuffer();
String str = null;
while ((str = reader.readLine()) != null) {
sb.append(str + "\n");
}
}
return sb.toString();
} catch (IOException ex) {
// 发邮件
} finally {
try {
if (conn != null) {
conn.disconnect();
}
if (reader != null) {
reader.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "北京";
}
/**
* 获得该IP对应的城市
*
* @param ipAddress
* IP地址
* @return
*/
public static String getIpAddress(String ipAddress) {
String url = "http://www.youdao.com/smartresult-xml/search.s?type=ip&q=" + ipAddress;// 210.51.45.99
return HttpProxy(url, "", "", "", "");
}
public static void main(String[] args) {
String result = getIpAddress("210.51.45.99");
if (!result.endsWith("北京")) {
Matcher m = Pattern.compile("<location>.*?</location>").matcher(result);
while (m.find()) {
System.out.println(m.group());
}
}
}
}