e8c3e370e58561c8592594b7b53cf41ef929b63b.svn-base
2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package yxy.timer.tool;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import com.alibaba.fastjson.JSONObject;
/***
* 获取IP与地区
*/
public class getArea {
public static void main(String[] args) {
System.out.println(getArea("185.40.172.16"));
}
/**
* 通过IP查询所在地区
*/
public static String getArea(String ip){
String IPArea="未知";
HttpURLConnection httpUrlConnection = null;
ByteArrayOutputStream baos = null;
InputStream in = null;
String path = ConfigPath.getCentreUrl();
try {
String url = path + "/webservice/ip?ip=" + ip;
URLConnection urlConnection = new URL(url).openConnection();
httpUrlConnection = (HttpURLConnection) urlConnection;
// 设置是否向httpUrlConnection输出,post请求,参数要放在http正文内,因此需要设为true,
// 默认情况下是false;
httpUrlConnection.setDoOutput(true);
// 设置是否从httpUrlConnection读入,默认情况下是true;
httpUrlConnection.setDoInput(true);
// 忽略缓存
httpUrlConnection.setUseCaches(false);
// 设定请求的方法为"POST",默认是GET
httpUrlConnection.setRequestMethod("POST");
// 获得响应状态
int responseCode = httpUrlConnection.getResponseCode();
String result = null;
if (HttpURLConnection.HTTP_OK == responseCode) {
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
in = httpUrlConnection.getInputStream();
while ((len = in.read(buffer)) != -1) {
baos.write(buffer, 0, len);
baos.flush();
}
result = baos.toString("UTF-8");
}
if (result != null) {
JSONObject data = JSONObject.parseObject(result);
if (data.getInteger("code") == 200) {
data = JSONObject.parseObject(data.getString("result"));
IPArea = data.getString("country")+data.getString("prov")+data.getString("city");//获取某ip所在城市
}
}
}catch (Exception e) {
//System.out.println("获取地区失败!");
} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
//System.out.println("获取地区失败!");
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
//System.out.println("获取地区失败!");
}
}
if (httpUrlConnection != null) {
httpUrlConnection.disconnect();
}
}
return IPArea;
}
}