溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

javaweb實(shí)現(xiàn)百度GPS定位接口(經(jīng)緯度)

發(fā)布時(shí)間:2020-09-14 02:37:21 來(lái)源:腳本之家 閱讀:454 作者:Asia1752 欄目:編程語(yǔ)言

百度web GPS定位(經(jīng)緯度)

注冊(cè)賬號(hào)及配置地址

http://lbsyun.baidu.com/apiconsole/key

主類 BaiduWebAPI

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.webber.cm.common.util.HttpClient;
import com.webber.cm.common.util.JsonUtil;

public class BaiduWebAPI {

 static Logger logger = Logger.getLogger(BaiduWebAPI.class);

 // 配置地址:http://lbsyun.baidu.com/apiconsole/key
 private static final String APP_ID = "18**********";
 private static final String AK = "XGXnh8tB7e*******************";

 public static void main(String[] args) {
 //BaiduWebAPI.ipLocation("127.0.0.1");
 BaiduWebAPI.gpsLocation("116.840213","39.196272");
 }

 // GPS接口
 public static String gpsLocation(String lng, String lat) {
 String result = null;
 try {
  String url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=MY_AK&output=json&coordtype=wgs84ll&location=LAT_VALUE,LNG_VALUE";
  url = url.replace("MY_AK", AK).replace("LNG_VALUE", lng).replace("LAT_VALUE", lat);
  String reqResult = HttpClient.doGet(url);
  System.out.println(reqResult);
  Map<String, Object> map = JsonUtil.parseJSON2Map(reqResult);
  Map ac = (Map) ((Map) map.get("result")).get("addressComponent");
  result = ac.get("city").toString() + ac.get("district").toString();
 } catch (Exception e) {
  logger.error("GPS接口異常:", e);
 }
 logger.info("GPS接口:{lng:" + lng + ",lat:" + lat + ",result:" + result + "}");
 return result;
 }

 // IP接口
 public static String ipLocation(String ip) {
 if(BaiduWebAPI.isLan(ip)) {
  return "內(nèi)網(wǎng)IP";
 }
 String result = null;
 try {
  String url = "http://api.map.baidu.com/location/ip?ak=MY_AK&ip=IP_VALUE&coor=bd09ll";
  url = url.replace("MY_AK", AK).replace("IP_VALUE", ip);
  String reqResult = decodeUnicode(HttpClient.doGet(url));
  System.out.println(reqResult);
  Map<String, Object> map = JsonUtil.parseJSON2Map(reqResult);
  result=((Map) map.get("content")).get("address").toString();
  result=result.replace("省", "").replace("市", "");
 } catch (Exception e) {
  logger.error("IP接口異常:", e);
 }
 logger.info("IP接口:{ip:" + ip + ",result:" + result + "}");
 return result;
 }

 // unicode轉(zhuǎn)化漢字
 public static String decodeUnicode(final String unicode) {
 StringBuffer string = new StringBuffer();

 String[] hex = unicode.split("\\\\u");

 for (int i = 0; i < hex.length; i++) {

  try {
  // 漢字范圍 \u4e00-\u9fa5 (中文)
  if (hex[i].length() >= 4) {// 取前四個(gè),判斷是否是漢字
   String chinese = hex[i].substring(0, 4);
   try {
   int chr = Integer.parseInt(chinese, 16);
   boolean isChinese = isChinese((char) chr);
   // 轉(zhuǎn)化成功,判斷是否在 漢字范圍內(nèi)
   if (isChinese) {// 在漢字范圍內(nèi)
    // 追加成string
    string.append((char) chr);
    // 并且追加 后面的字符
    String behindString = hex[i].substring(4);
    string.append(behindString);
   } else {
    string.append(hex[i]);
   }
   } catch (NumberFormatException e1) {
   string.append(hex[i]);
   }

  } else {
   string.append(hex[i]);
  }
  } catch (NumberFormatException e) {
  string.append(hex[i]);
  }
 }
 return string.toString();
 }

 /**
 * 判斷是否為中文字符
 * 
 * @param c
 * @return
 */
 public static boolean isChinese(char c) {
 Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
 if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
  || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
  || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
  || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
  || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
  || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
  return true;
 }
 return false;
 }
 
 // 是否為局域網(wǎng)
 private static Boolean isLan(String ip) {
    if("127.0.0.1".equals(ip)) {
     return true;
    }
    
    if (!StringUtils.isEmpty(ip) && ip.length() > 15) {
      ip = ip.substring(0, ip.indexOf(","));
    }
    /*
     * 判斷客戶單IP地址是否為內(nèi)網(wǎng)地址
     * 內(nèi)網(wǎng)IP網(wǎng)段:
     * 10.0.0.0-10.255.255.255
     * 172.16.0.0-172.31.255.255
     * 192.168.0.0-192.168.255.255
     */
    String reg = "^(192\\.168|172\\.(1[6-9]|2\\d|3[0,1]))(\\.(2[0-4]\\d|25[0-5]|[0,1]?\\d?\\d)){2}$|^10(\\.([2][0-4]\\d|25[0-5]|[0,1]?\\d?\\d)){3}$";
    Pattern p = Pattern.compile(reg);
    Matcher matcher = p.matcher(ip);
    return matcher.find();
  }
}

工具類 HttpClient

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpClient {
 
 public static void main(String[] args) {
 
 }
 
 public static String doGet(String httpurl) {
 HttpURLConnection connection = null;
 InputStream is = null;
 BufferedReader br = null;
 String result = null;// 返回結(jié)果字符串
 try {
  // 創(chuàng)建遠(yuǎn)程url連接對(duì)象
  URL url = new URL(httpurl);
  // 通過(guò)遠(yuǎn)程url連接對(duì)象打開(kāi)一個(gè)連接,強(qiáng)轉(zhuǎn)成httpURLConnection類
  connection = (HttpURLConnection) url.openConnection();
  // 設(shè)置連接方式:get
  connection.setRequestMethod("GET");
  // 設(shè)置連接主機(jī)服務(wù)器的超時(shí)時(shí)間:15000毫秒
  connection.setConnectTimeout(15000);
  // 設(shè)置讀取遠(yuǎn)程返回的數(shù)據(jù)時(shí)間:60000毫秒
  connection.setReadTimeout(60000);
  // 發(fā)送請(qǐng)求
  connection.connect();
  // 通過(guò)connection連接,獲取輸入流
  if (connection.getResponseCode() == 200) {
  is = connection.getInputStream();
  // 封裝輸入流is,并指定字符集
  br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  // 存放數(shù)據(jù)
  StringBuffer sbf = new StringBuffer();
  String temp = null;
  while ((temp = br.readLine()) != null) {
   sbf.append(temp);
   sbf.append("\r\n");
  }
  result = sbf.toString();
  }
 } catch (MalformedURLException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 } finally {
  // 關(guān)閉資源
  if (null != br) {
  try {
   br.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
  }

  if (null != is) {
  try {
   is.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
  }

  connection.disconnect();// 關(guān)閉遠(yuǎn)程連接
 }

 return result;
 }

 public static String doPost(String httpUrl, String param) {
 HttpURLConnection connection = null;
 InputStream is = null;
 OutputStream os = null;
 BufferedReader br = null;
 String result = null;
 try {
  URL url = new URL(httpUrl);
  // 通過(guò)遠(yuǎn)程url連接對(duì)象打開(kāi)連接
  connection = (HttpURLConnection) url.openConnection();
  // 設(shè)置連接請(qǐng)求方式
  connection.setRequestMethod("POST");
  // 設(shè)置連接主機(jī)服務(wù)器超時(shí)時(shí)間:15000毫秒
  connection.setConnectTimeout(15000);
  // 設(shè)置讀取主機(jī)服務(wù)器返回?cái)?shù)據(jù)超時(shí)時(shí)間:60000毫秒
  connection.setReadTimeout(60000);

  // 默認(rèn)值為:false,當(dāng)向遠(yuǎn)程服務(wù)器傳送數(shù)據(jù)/寫(xiě)數(shù)據(jù)時(shí),需要設(shè)置為true
  connection.setDoOutput(true);
  // 默認(rèn)值為:true,當(dāng)前向遠(yuǎn)程服務(wù)讀取數(shù)據(jù)時(shí),設(shè)置為true,該參數(shù)可有可無(wú)
  connection.setDoInput(true);
  // 設(shè)置傳入?yún)?shù)的格式:請(qǐng)求參數(shù)應(yīng)該是 name1=value1&name2=value2 的形式。
  connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  // 設(shè)置鑒權(quán)信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
  connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
  // 通過(guò)連接對(duì)象獲取一個(gè)輸出流
  os = connection.getOutputStream();
  // 通過(guò)輸出流對(duì)象將參數(shù)寫(xiě)出去/傳輸出去,它是通過(guò)字節(jié)數(shù)組寫(xiě)出的
  os.write(param.getBytes());
  // 通過(guò)連接對(duì)象獲取一個(gè)輸入流,向遠(yuǎn)程讀取
  if (connection.getResponseCode() == 200) {

  is = connection.getInputStream();
  // 對(duì)輸入流對(duì)象進(jìn)行包裝:charset根據(jù)工作項(xiàng)目組的要求來(lái)設(shè)置
  br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

  StringBuffer sbf = new StringBuffer();
  String temp = null;
  // 循環(huán)遍歷一行一行讀取數(shù)據(jù)
  while ((temp = br.readLine()) != null) {
   sbf.append(temp);
   sbf.append("\r\n");
  }
  result = sbf.toString();
  }
 } catch (MalformedURLException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 } finally {
  // 關(guān)閉資源
  if (null != br) {
  try {
   br.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
  }
  if (null != os) {
  try {
   os.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
  }
  if (null != is) {
  try {
   is.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
  }
  // 斷開(kāi)與遠(yuǎn)程地址url的連接
  connection.disconnect();
 }
 return result;
 }
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI