高德地圖web端筆記;發送http請求的工具類


1.查詢所有電子圍欄

package com.skjd.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class HttpUtils {
    
    // 代理服務器的HTTP請求協議,客戶端真實IP字段名稱
        public static final String X_REAL_IP = "x-forwarded-for";

    public static String get(final String url) throws Exception {
        String result = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpclient.execute(httpGet);
            try {
                System.out.println(response.getStatusLine());
                HttpEntity entity = response.getEntity();
                // do something useful with the response body
                // and ensure it is fully consumed
                result = org.apache.http.util.EntityUtils.toString(entity);
                org.apache.http.util.EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }

        return result;
    }

    public static String post(final String url, final Map<String, String> param) throws Exception {
        String result = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost("http://httpbin.org/post");
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();

            for (String key : param.keySet()) {
                nvps.add(new BasicNameValuePair(key, param.get(key)));
            }

            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                System.out.println(response.getStatusLine());
                HttpEntity entity = response.getEntity();
                // do something useful with the response body
                // and ensure it is fully consumed
                result = org.apache.http.util.EntityUtils.toString(entity);
                org.apache.http.util.EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        return result;
    }

    
    /**
     * 發送POST請求的方法
     */
    public static String sendPostRequest(String url,String param){
        HttpURLConnection httpURLConnection = null;
        OutputStream out = null; //
        InputStream in = null;   //
        int responseCode = 0;    //遠程主機響應的HTTP狀態碼
        String result="";
        try{
            URL sendUrl = new URL(url);
            httpURLConnection = (HttpURLConnection)sendUrl.openConnection();
            //post方式請求
            httpURLConnection.setRequestMethod("POST");
            //設置頭部信息
            httpURLConnection.setRequestProperty("headerdata", "ceshiyongde");
            //一定要設置 Content-Type 要不然服務端接收不到參數
            httpURLConnection.setRequestProperty("Content-Type", "application/Json; charset=UTF-8");
            //指示應用程序要將數據寫入URL連接,其值默認為false(是否傳參)
            httpURLConnection.setDoOutput(true);
            //httpURLConnection.setDoInput(true);       
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setConnectTimeout(30000); //30秒連接超時
            httpURLConnection.setReadTimeout(30000);    //30秒讀取超時
            //獲取輸出流
            out = httpURLConnection.getOutputStream();
            //輸出流里寫入POST參數
            out.write(param.getBytes());
            out.flush();
            out.close();
            responseCode = httpURLConnection.getResponseCode();
            BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"UTF-8"));
            result =br.readLine();
        }catch(Exception e) {
            e.printStackTrace();      
      }
    return result;
      
  }
    
    
    /**
     * 發送GET請求的方法
     */
    public static String sendPostRequestGet(String url){
        HttpURLConnection httpURLConnection = null;
        OutputStream out = null; //
        InputStream in = null;   //
        int responseCode = 0;    //遠程主機響應的HTTP狀態碼
        String result="";
        try{
            URL sendUrl = new URL(url);
            httpURLConnection = (HttpURLConnection)sendUrl.openConnection();
            //post方式請求
            httpURLConnection.setRequestMethod("GET");
            //設置頭部信息
            httpURLConnection.setRequestProperty("headerdata", "ceshiyongde");
            //一定要設置 Content-Type 要不然服務端接收不到參數
            httpURLConnection.setRequestProperty("Content-Type", "application/Json; charset=UTF-8");
            //指示應用程序要將數據寫入URL連接,其值默認為false(是否傳參)
            httpURLConnection.setDoOutput(true);
            //httpURLConnection.setDoInput(true); 
            
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setConnectTimeout(30000); //30秒連接超時
            httpURLConnection.setReadTimeout(30000);    //30秒讀取超時
            responseCode = httpURLConnection.getResponseCode();
            BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"UTF-8"));
            result =br.readLine();
        }catch(Exception e) {
            e.printStackTrace();        
        }
        return result;
        
    }
    
    /**
     * for nigx返向代理構造 獲取客戶端IP地址
     * @param request
     * @return
     */
    public static String getRemoteHost(HttpServletRequest request){
        String ip = request.getHeader(X_REAL_IP);
        if(ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
            ip = request.getRemoteAddr();
        }
        return ip.split(",")[0];
    }
    
    
    public static void main(String[] args) {
        try {
            System.out.println(get("http://www.baidu.com"));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
http請求工具類
    /**
     * 根據key查詢所有的圍欄
     * 返回所有圍欄的信息
     * @param pd
     * @return
     * @throws Exception 
     */
    public List<Map<String,Object>> select(Map<String,Object> pd) throws Exception{
        Gson gson=new Gson();
        String key=pd.get("key").toString();
        String url="http://restapi.amap.com/v4/geofence/meta?key="
                +key;
         //請求返回的參數
        String data=HttpUtils.sendPostRequestGet(url);
        //轉為對象便於獲取
        Map<String,Object> dataJson = gson.fromJson(data, HashMap.class);
        Map<String, Object> map=(LinkedTreeMap)dataJson.get("data");
        List<Map<String,Object>> list = (List)map.get("rs_list");
        
        return list;
    }    

2.創建圍欄

/**
     * 傳入對應格式的坐標區域,創建一個圍欄;返回status(新增成功0,已存在返回1;失敗返回2);若新增成功則返回gid;message信息
     */
    public static  PageData xyUtil(PageData pd){
        PageData pd2=new PageData();
        pd.put("key", "be8e6c802d51a4be29c99be895d8c2c7");
        //數據庫讀取的坐標參數
        /*114.288221,30.593268#114.321866,30.580559#114.311223,30.560015#114.291278,30.602487#*/
        //第三方接口要求的格式:lon1,lat1;lon2,lat2;lon3,lat3(3<=點個數<=5000)
        //將#號換為;
        String points = pd.getString("points").replace("#", ";");
        String key=pd.getString("key");
        String name=pd.getString("name1");
        PageData pd3=new PageData();
        pd3.put("points", points);
        pd3.put("name", name);
        /*pd3.put("valid_time ", DateUtil.getDay());設置過期時間、默認90天*/
        pd3.put("repeat", "Mon,Tues,Wed,Thur,Fri,Sat,Sun");//可以指定每天的監控時間段和一周內監控的日期
           Gson gson=new Gson();
            //傳入的參數
            String param=gson.toJson(pd3);
            String url="http://restapi.amap.com/v4/geofence/meta?key="
                    + key
                    + "&type=ajaxRequest";
            String data=HttpUtil.sendPostRequest(url,param);
                    //請求回來的數據
                    System.out.println(data);
                    PageData data2 = gson.fromJson(data, pd.getClass());
                    PageData data3 = gson.fromJson(data2.get("data").toString(), pd.getClass());
                    //狀態為0說明新增成功!
                  if(data3.get("status").toString().equals("0.0")){
                      pd2.put("status", "0");
                      pd2.put("gid", data3.get("gid").toString());
                //返回狀態106.0說明已存在,則查詢此區域的gid
                  }else if(data3.get("status").toString().equals("106.0")){
                      pd2.put("status", "1");
                  }else{
                      pd2.put("status", "2");
                  }
                  pd2.put("message", data3.get("message").toString());
        return pd2;
    }

3.更新圍欄

/**
     * 更新圍欄;傳入圍欄名稱name;gid;傳入圍欄坐標點points
     * @param pd
     * @return 返回status
     */
    public static PageData xyupdata(PageData pd){
        PageData pd2=new PageData();
        pd.put("key", "be8e6c802d51a4be29c99be895d8c2c7");
        String key=pd.getString("key");
    /*    String gid=pd.getString("gid");*/
        String gid=pd.getString("gid");
        pd2.put("repeat", "Mon,Tues,Wed,Thur,Fri,Sat,Sun");
        pd2.put("points",pd.getString("points").replace("#", ";"));
        pd2.put("name", pd.getString("name1"));
            
         Gson gson=new Gson();
            //傳入的參數
            String param=gson.toJson(pd2);        
            String url="http://restapi.amap.com/v4/geofence/meta?key="
                    + key+"&gid="
                    +gid
                    + "&type=ajaxRequest&method=patch";
            String data=HttpUtil.sendPostRequest(url,param);
            System.out.println(data);
            PageData data2 = gson.fromJson(data, pd.getClass());
            PageData data3 = gson.fromJson(data2.get("data").toString(), pd.getClass());
        return data3;
    }

4.刪除圍欄

    /**
     * 刪除圍欄;傳入圍欄名稱gid;
     * @param pd
     * @return 返回status
     */
    public static PageData xydel(PageData pd){
        PageData pd2=new PageData();
        pd.put("key", "be8e6c802d51a4be29c99be895d8c2c7");
        String key=pd.getString("key");
        /*    String gid=pd.getString("gid");*/
        String gid=pd.getString("gid");        
        Gson gson=new Gson();
        //傳入的參數
        String param=gson.toJson(pd2);        
        String url="http://restapi.amap.com/v4/geofence/meta?key="
                + key+"&gid="
                +gid
                + "&type=ajaxRequest&method=delete";
        String data=HttpUtil.sendPostRequest(url,param);
        System.out.println(data);
        PageData data2 = gson.fromJson(data, pd.getClass());
        PageData data3 = gson.fromJson(data2.get("data").toString(), pd.getClass());
        return data3;
    }

5.查詢一個坐標是否在圍欄內;如果需要查詢是否在指定的圍欄內,需要做進一步處理

    /**需要傳入參數key;diu(唯一設備號);時間戳;坐標點
     *返回 狀態status(0表示在范圍內;1表示不在范圍內)
     *如果在范圍內,則返回圍欄列表,帶有gid和name
     * @throws Exception 
     */
    public Map<String,Object> xyTest(Map<String,Object> pd) throws Exception{
        Map<String,Object> pd2=new HashMap();
        
        //坐標點
        String locations =pd.get("locations").toString();
        //key
        String key=pd.get("key").toString();
        //設備唯一標識
        String diu=pd.get("diu").toString();
        //時間戳
        String time="1484816232";    
           Gson gson=new Gson();
            String url="http://restapi.amap.com/v4/geofence/status?"
                    + "key="+key
                    + "&diu="+diu
                    + "&locations="+locations+","
                    + time;
            //請求返回的參數
            String data=HttpUtils.sendPostRequestGet(url);
           //轉為對象便於獲取
            Map<String,Object> dataJson = gson.fromJson(data, HashMap.class);
            Map<String, Object> map=(LinkedTreeMap)dataJson.get("data");    
            
                //獲取圍欄事件列表;如果為空說明不在圍欄內
        if(map.get("fencing_event_list")==null||((List)map.get("fencing_event_list")).size()<1){
                pd2.put("status", "1");
                return pd2;
            }
            //如果不為空,則獲取里面的返回值
        List<Map<String,Object>> list = (List) map.get("fencing_event_list");
                List<Map<String,Object>> list2 = new ArrayList<>();
                for(int i=0;i<list.size();i++){
                    Map<String,Object> pd3=new HashMap();
                    Map<String,Object> map2 = list.get(i);
                    //如果高德地圖api返回的狀態為in說明在范圍內
                    if(map2.get("client_status").toString().equals("in")){
                        //圍欄信息
                        Map<String,Object> map3 =(Map)map2.get("fence_info");
                    
                        //添加全局圍欄gid值;
                        pd3.put("fence_gid",map3.get("fence_gid").toString());
                        //添加圍欄名稱
                        pd3.put("fence_name", map3.get("fence_name").toString()); 
                        list2.add(pd3);
                    }               
                }
                //添加狀態值
            pd2.put("status", "0");
            pd2.put("list", list2);
            return pd2;
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM