IP 에 따라 주소 정보 가 져 오기

3637 단어 자바

package com.lee;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;
/**
* IP
*/
public class IPSeeker {
public void getAddresses(String content, String encodingString)
throws UnsupportedEncodingException {
// pconline
String urlStr = "http://ip.taobao.com/service/getIpInfo.php";
// http://whois.pconline.com.cn IP
String returnStr = this.getResult(urlStr, content, encodingString);
if (returnStr != null) {
System.out.println(returnStr);
JSONObject json=null;
try {
json = new JSONObject(returnStr);
System.out.println(json.optJSONObject("data").getString("country"));
System.out.println(json.optJSONObject("data").getString("area"));
System.out.println(json.optJSONObject("data").getString("region"));
System.out.println(json.optJSONObject("data").getString("city"));
System.out.println(json.optJSONObject("data").getString("county"));
System.out.println(json.optJSONObject("data").getString("isp"));
} catch (JSONException e){
e.printStackTrace();
}
}
}
/**
* @param urlStr
*
* @param content
* :name=xxx&pwd=xxx
* @param encoding
* 。 GBK,UTF-8
* @return
*/
private String getResult(String urlStr, String content, String encoding) {
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();//
connection.setConnectTimeout(2000);// ,
connection.setReadTimeout(2000);// ,
connection.setDoOutput(true);// true|false
connection.setDoInput(true);// true|false
connection.setRequestMethod("POST");// POST|GET
connection.setUseCaches(false);// true|false
connection.connect();//
DataOutputStream out = new DataOutputStream(connection.getOutputStream());//
out.writeBytes(content);// , name=xxx&pwd=xxx
out.flush();//
out.close();//
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(), encoding));//
// , BufferedReader
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();//
}
}
return null;
}

//
public static void main(String[] args) throws UnsupportedEncodingException {
IPSeeker seeker = new IPSeeker();
// ip 219.136.134.157 = = = = =
String ip = "219.136.134.157";
try {
seeker.getAddresses("ip="+ip, "GBK");
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}

좋은 웹페이지 즐겨찾기