java通過外網ip擷取本地城市地理位置__java

來源:互聯網
上載者:User

一.擷取外網IP

 public static String getWebIp(String strUrl) {
strUrl="http://www.ip138.com/ip2city.asp"; 
  try {


   URL url = new URL(strUrl);


   BufferedReader br = new BufferedReader(new InputStreamReader(url


   .openStream()));


   String s = "";


   StringBuffer sb = new StringBuffer("");
   
   String webContent = "";


   while ((s = br.readLine()) != null) {
    sb.append(s + "\r\n");


   }


   br.close();
   webContent = sb.toString();
   int start = webContent.indexOf("[")+1;
   int end = webContent.indexOf("]");
   webContent = webContent.substring(start,end);
   
   return webContent;


  } catch (Exception e) {
   e.printStackTrace();
   return "error open url:" + strUrl;


  }
 }

二.通過外網ip擷取地理位置的方法


1.import java.io.BufferedReader;

import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


import org.json.JSONObject;


public class AddressUtils {


public String getAddress(String params, String encoding) throws Exception{

String path = "http://ip.taobao.com/service/getIpInfo.php";

String returnStr = this.getRs(path, params, encoding);

JSONObject json=null;

if(returnStr != null){

json = new JSONObject(returnStr);

if("0".equals(json.get("code").toString())){

StringBuffer buffer = new StringBuffer();

//buffer.append(decodeUnicode(json.optJSONObject("data").getString("country")));//國家

//buffer.append(decodeUnicode(json.optJSONObject("data").getString("area")));//地區

buffer.append(decodeUnicode(json.optJSONObject("data").getString("region")));//省份

buffer.append(decodeUnicode(json.optJSONObject("data").getString("city")));//市區

buffer.append(decodeUnicode(json.optJSONObject("data").getString("county")));//地區





return buffer.toString();

}else{

return "擷取地址失敗�?";

}

}

return null;

}
/**
* 從url擷取結果
* @param path
* @param params
* @param encoding
* @return
*/
public String getRs(String path, String params, String encoding){

URL url = null;

HttpURLConnection connection = null;

try {

url = new URL(path);

connection = (HttpURLConnection)url.openConnection();// 建立串連執行個體

connection.setConnectTimeout(200000);// 設定連線逾時時間,單位毫�?

connection.setReadTimeout(200000);// 設定讀取資料逾時時間,單位毫�?

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();

String line = "";

while ((line = reader.readLine())!= null) {

buffer.append(line);

}

reader.close();

return buffer.toString();

} catch (Exception e) {

e.printStackTrace();

}finally{

connection.disconnect();// 關閉串連

}

return null;
}
/**
* 字元轉碼
* @param theString
* @return
*/
public static String decodeUnicode(String theString){

char aChar;

int len = theString.length();

StringBuffer buffer = new StringBuffer(len);

for (int i = 0; i < len;) {

aChar = theString.charAt(i++);

if(aChar == '\\'){

aChar = theString.charAt(i++);

if(aChar == 'u'){

int val = 0;

for(int j = 0; j < 4; j++){

aChar = theString.charAt(i++);

switch (aChar) {

case '0':

case '1':

case '2':

case '3':

case '4':

case '5':

case '6':

case '7':

case '8':

case '9':

val = (val << 4) + aChar - '0';

break;

case 'a':

case 'b':

case 'c':

case 'd':

case 'e':

case 'f':

val = (val << 4) + 10 + aChar - 'a';
      
break;

case 'A':

case 'B':

case 'C':

case 'D':

case 'E':

case 'F':
 
val = (val << 4) + 10 + aChar - 'A';
      
break;
      
default:

throw new IllegalArgumentException(
        
"Malformed      encoding.");
   }

}

buffer.append((char) val);

}else{

if(aChar == 't'){

aChar = '\t';
}

if(aChar == 'r'){

aChar = '\r';
}

if(aChar == 'n'){

aChar = '\n';
}

if(aChar == 'f'){

aChar = '\f';

}

buffer.append(aChar);
}

}else{

buffer.append(aChar);

}

}

return buffer.toString();

}


}

2.通過方法擷取地理位置

public class GetCity {
public String getCt(String ip){
AddressUtils addressUtils = new AddressUtils();
String address = "";
try {
 
address = addressUtils.getAddress("ip="+ip, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return address;
}
}

例如

public class Test1 {
public static void main(String[] args) throws UnknownHostException {
GetCity gc=new GetCity();
ListIP ip=new ListIP();
System.out.println(ip.getWebIp("http://www.ip138.com/ip2city.asp"));
String str=gc.getCt(ip.getWebIp("http://www.ip138.com/ip2city.asp"));
System.out.println(str);
//String ip = InetAddress.getLocalHost().getHostAddress();
//String ip = InetAddress.getLocalHost().getHostAddress();
        //System.out.println(ip);
}


}

運行結果為

59.51.18.196
湖南省衡陽市

 注意須匯入other-JSON-20090211.jar包

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.