獲取請求IP所在的國家和城市
阿新 • • 發佈:2019-01-25
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class AddressUtils {
public static void main(String[] args) {
try {
AddressUtils addressUtils = new AddressUtils();
String ip = "116.226.214.246" ;
String address = addressUtils.getAddress("ip=" + ip, "utf-8");
String country = address.substring(address.indexOf("country")+10, address.indexOf("area")-3);
String city = address.substring(address.indexOf("city")+7, address.indexOf("county")-3);
System.out.println(country+"•" +city);
} catch (Exception e) {
e.printStackTrace();
}
}
public String getAddress(String params, String encoding){
HttpURLConnection connection = null;// 新建連線例項
try {
URL url = new URL("http://ip.taobao.com/service/getIpInfo.php" );
connection = (HttpURLConnection)url.openConnection();
connection.setConnectTimeout(5000);// 設定連線超時時間,單位毫秒
connection.setReadTimeout(5000);// 設定讀取資料超時時間,單位毫秒
connection.setDoInput(true);// 是否開啟輸出流 true|false
connection.setDoOutput(true);// 是否開啟輸入流true|false
connection.setRequestMethod("POST");// 提交方法POST|GET
connection.setUseCaches(false);// 是否快取true|false
connection.connect();// 開啟連線埠
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(params); out.flush(); out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),encoding));
StringBuffer buffer = new StringBuffer();
for (String line = "";(line = reader.readLine())!= null;) buffer.append(line);
reader.close();
return buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}finally{
connection.disconnect();// 關閉連線
}
return null;
}
}