Java obtains local city geographic location through extranet IP __java

Source: Internet
Author: User
Tags readline stringbuffer

I. Get the extranet 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;


}
}

Two. Approach to geographic location via extranet 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"))/Country

Buffer.append (Decodeunicode (Json.optjsonobject ("Data"). GetString ("area"));/region

Buffer.append (Decodeunicode) (Json.optjsonobject ("Data"). GetString ("region"));/Province

Buffer.append (Decodeunicode) (Json.optjsonobject ("Data"). GetString ("City"))

Buffer.append (Decodeunicode (Json.optjsonobject ("Data"). GetString ("county"));/region





return buffer.tostring ();

}else{

Return "Get address failed?";

}

}

return null;

}
/**
* Get results from 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 ();//New Connection instance

Connection.setconnecttimeout (200000)//Set the connection timeout time, Unit no?

Connection.setreadtimeout (200000)//Set the Read Data timeout, Unit no?

Connection.setdoinput (TRUE);//is the output turned on? True|false

Connection.setdooutput (TRUE);//whether to open the input stream true|false

Connection.setrequestmethod ("POST");//Submit Method post| Get

Connection.setusecaches (false);//whether to cache True|false

Connection.connect ()//Open connection port

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 ()//close connection

}

return null;
}
/**
* Character Transfer code
* @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) + + Achar-' a ';

Break

Case ' A ':

Case ' B ':

Case ' C ':

Case ' D ':

Case ' E ':

Case ' F ':

val = (val << 4) + + 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. Obtaining geographical location by means of

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;
}
}

For example

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


}

Run result is

59.51.18.196
Hengyang, Hunan Province

Note that the Other-json-20090211.jar package must be imported

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.