package com.example.core.xk.controller;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.json.JSONException;
import org.springframework.stereotype.Controller;
import com.alibaba.fastjson.JSONObject;
@Controller
public class GetPosition {
private static final String BAIDU_APP_KEY = "WhFBA4PhFBShN8ako23Psd5MmC3Txios";
public static String getPublicIP() {
String ip = "";
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return ip;
}
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
public static Map<String, String> getLatitude(String address) {
try {
address = URLEncoder.encode(address, "UTF-8");
URL resjson = new URL(
"http://api.map.baidu.com/geocoder?address=" + address + "&output=json&key=" + BAIDU_APP_KEY);
BufferedReader in = new BufferedReader(new InputStreamReader(resjson.openStream()));
String res;
StringBuilder sb = new StringBuilder("");
while ((res = in.readLine()) != null) {
sb.append(res.trim());
}
in.close();
String str = sb.toString();
if (str != null && !str.equals("")) {
Map<String, String> map = null;
int lngStart = str.indexOf("lng\":");
int lngEnd = str.indexOf(",\"lat");
int latEnd = str.indexOf("},\"precise");
if (lngStart > 0 && lngEnd > 0 && latEnd > 0) {
String longitude = str.substring(lngStart + 5, lngEnd);
String latitude = str.substring(lngEnd + 7, latEnd);
map = new HashMap<String, String>();
map.put("longitude", longitude);
map.put("latitude", latitude);
return map;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = JSONObject.parseObject(jsonText);
return json;
} finally {
is.close();
}
}
private static 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);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(content);
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 (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
public static String decodeUnicode(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len);
for (int x = 0; x < len;) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException("Malformedencoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't') {
aChar = '\t';
} else if (aChar == 'r') {
aChar = '\r';
} else if (aChar == 'n') {
aChar = '\n';
} else if (aChar == 'f') {
aChar = '\f';
}
outBuffer.append(aChar);
}
} else {
outBuffer.append(aChar);
}
}
return outBuffer.toString();
}
public static String getAddrName(String content, String encodingString) throws IOException {
String urlStr = "http://ip.taobao.com/service/getIpInfo.php";
String returnStr = GetPosition.getResult(urlStr, content, encodingString);
if (returnStr != null) {
System.out.println(returnStr);
String[] temp = returnStr.split(",");
if (temp.length < 3) {
return "0";
}
String region = (temp[5].split(":"))[1].replaceAll("\"", "");
region = decodeUnicode(region);
String country = "";
String area = "";
String city = "";
String county = "";
String isp = "";
for (int i = 0; i < temp.length; i++) {
switch (i) {
case 1:
country = (temp[i].split(":"))[2].replaceAll("\"", "");
country = decodeUnicode(country);
break;
case 3:
area = (temp[i].split(":"))[1].replaceAll("\"", "");
area = decodeUnicode(area);
break;
case 5:
region = (temp[i].split(":"))[1].replaceAll("\"", "");
region = decodeUnicode(region);
break;
case 7:
city = (temp[i].split(":"))[1].replaceAll("\"", "");
city = decodeUnicode(city);
break;
case 9:
county = (temp[i].split(":"))[1].replaceAll("\"", "");
county = decodeUnicode(county);
break;
case 11:
isp = (temp[i].split(":"))[1].replaceAll("\"", "");
isp = decodeUnicode(isp);
break;
}
}
System.out.println(country + "=" + area + "=" + region + "=" + city + "=" + county + "=" + isp);
return region;
}
return null;
}
public static String getAddrByBaiduAPI(String Ip) throws JSONException, IOException {
JSONObject json = GetPosition
.readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=WhFBA4PhFBShN8ako23Psd5MmC3Txios&ip=" + Ip);
JSONObject content = ((JSONObject) json).getJSONObject("content");
JSONObject addr_detail = ((JSONObject) content).getJSONObject("address_detail");
String city = addr_detail.getString("province").toString() + addr_detail.getString("city").toString()
+ addr_detail.getString("street").toString();
return city;
}
}