百度地图API 云存储·LBS.云 工具类封装(Java)

百度地图API 云存储·LBS.云 工具类封装(Java)

一、设计思路

根据百度地图 云存储API 以经典的DAO设计模式编写,目录如下:
百度地图API 云存储·LBS.云 工具类封装(Java)_第1张图片

二、源码部分

1、HttpRequestor.java

package com.xeonmic.lbs.util;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;


public class HttpRequestor {

    private String charset = "utf-8";
    private Integer connectTimeout = null;
    private Integer socketTimeout = null;
    private String proxyHost = null;
    private Integer proxyPort = null;

    /**
     * Do GET request
     * @param url
     * @return
     * @throws Exception
     * @throws IOException
     */
    public String doGet(String url) throws Exception {

        URL localURL = new URL(url);

        URLConnection connection = openConnection(localURL);
        HttpURLConnection httpURLConnection = (HttpURLConnection)connection;

        httpURLConnection.setRequestProperty("Accept-Charset", charset);
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
       // BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
        if (httpURLConnection.getResponseCode() >= 300) {
            throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
        }

        try {
            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
            reader = new BufferedReader(inputStreamReader);

            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }

        } finally {

            if (reader != null) {
                reader.close();
            }

            if (inputStreamReader != null) {
                inputStreamReader.close();
            }

            if (inputStream != null) {
                inputStream.close();
            }

        }

        return resultBuffer.toString();
    }

    /**
     * Do POST request
     * @param url
     * @param parameterMap
     * @return
     * @throws Exception 
     */
    public String doPost(String url, Map parameterMap) throws Exception {

        /* Translate parameter map to parameter date string */
        StringBuffer parameterBuffer = new StringBuffer();
        if (parameterMap != null) {
            Iterator iterator = parameterMap.keySet().iterator();
            String key = null;
            String value = null;
            while (iterator.hasNext()) {
                key = iterator.next();
                if (parameterMap.get(key) != null) {
                    value =parameterMap.get(key).toString();
                } else {
                    value = "";
                }

                parameterBuffer.append(key).append("=").append(value);
                if (iterator.hasNext()) {
                    parameterBuffer.append("&");
                }
            }
        }

        System.out.println("POST parameter : " + parameterBuffer.toString());

        URL localURL = new URL(url);

        URLConnection connection = openConnection(localURL);
        HttpURLConnection httpURLConnection = (HttpURLConnection)connection;

        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Accept-Charset", charset);
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));

        OutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;

        try {
            outputStream = httpURLConnection.getOutputStream();
            outputStreamWriter = new OutputStreamWriter(outputStream);

            outputStreamWriter.write(parameterBuffer.toString());
            outputStreamWriter.flush();

            if (httpURLConnection.getResponseCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
            }

            inputStream = httpURLConnection.getInputStream();
           // inputStreamReader = new InputStreamReader(inputStream);
            inputStreamReader = new InputStreamReader(inputStream,"utf-8");
            reader = new BufferedReader(inputStreamReader);

            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }

        } finally {

            if (outputStreamWriter != null) {
                outputStreamWriter.close();
            }

            if (outputStream != null) {
                outputStream.close();
            }

            if (reader != null) {
                reader.close();
            }

            if (inputStreamReader != null) {
                inputStreamReader.close();
            }

            if (inputStream != null) {
                inputStream.close();
            }

        }

        return resultBuffer.toString();
    }

    private URLConnection openConnection(URL localURL) throws IOException {
        URLConnection connection;
        if (proxyHost != null && proxyPort != null) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            connection = localURL.openConnection(proxy);
        } else {
            connection = localURL.openConnection();
        }
        return connection;
    }

    /**
     * Render request according setting
     * @param request
     */
    private void renderRequest(URLConnection connection) {

        if (connectTimeout != null) {
            connection.setConnectTimeout(connectTimeout);
        }

        if (socketTimeout != null) {
            connection.setReadTimeout(socketTimeout);
        }

    }

    /*
     * Getter & Setter
     */
    public Integer getConnectTimeout() {
        return connectTimeout;
    }

    public void setConnectTimeout(Integer connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public Integer getSocketTimeout() {
        return socketTimeout;
    }

    public void setSocketTimeout(Integer socketTimeout) {
        this.socketTimeout = socketTimeout;
    }

    public String getProxyHost() {
        return proxyHost;
    }

    public void setProxyHost(String proxyHost) {
        this.proxyHost = proxyHost;
    }

    public Integer getProxyPort() {
        return proxyPort;
    }

    public void setProxyPort(Integer proxyPort) {
        this.proxyPort = proxyPort;
    }

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

}

2、LBSPoiDAO.java

package com.xeonmic.lbs.dao;

import com.xeonmic.lbs.vo.POICreateCustomDate;
import com.xeonmic.lbs.vo.POICreateJson;
import com.xeonmic.lbs.vo.POIDeleteJson;
import com.xeonmic.lbs.vo.POIDeleteObject;
import com.xeonmic.lbs.vo.POIFindByIdJson;
import com.xeonmic.lbs.vo.POIFindJson;
import com.xeonmic.lbs.vo.POIFindObject;
import com.xeonmic.lbs.vo.POIUpDateCustomDate;
import com.xeonmic.lbs.vo.POIUpdateJson;

public interface LBSPoiDAO {
    /**
     * 创建数据(create poi)接口
     * @param poi
     * @return
     */
    public POICreateJson POICreate(POICreateCustomDate poi);
    /**
     * 查询指定条件的数据(poi)列表接口
     * @param keys
     * @return
     */
    public POIFindJson POIFind(POIFindObject keys) ;
    /**
     * 查询指定id的数据(poi)详情接口
     * @param id
     * @return
     */
    public POIFindByIdJson POIFindById(int id);
    /**
     * 修改数据(poi)接口
     * @param poi
     * @return
     */
    public POIUpdateJson POIUpDate(POIUpDateCustomDate poi);
    /**
     * 删除数据(poi)接口(支持批量)
     * @param poi
     * @return
     */
    public POIDeleteJson POIDelete(POIDeleteObject poi);



}

3、LBSPoiDAOImpl.java

/**
 * 
 */
package com.xeonmic.lbs.dao.impl;



import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.xeonmic.lbs.dao.LBSPoiDAO;
import com.xeonmic.lbs.util.HttpRequestor;
import com.xeonmic.lbs.vo.LBSINFO;
import com.xeonmic.lbs.vo.POI;
import com.xeonmic.lbs.vo.POICreateCustomDate;
import com.xeonmic.lbs.vo.POICreateJson;
import com.xeonmic.lbs.vo.POIDeleteJson;
import com.xeonmic.lbs.vo.POIDeleteObject;
import com.xeonmic.lbs.vo.POIFindByIdJson;
import com.xeonmic.lbs.vo.POIFindJson;
import com.xeonmic.lbs.vo.POIFindObject;
import com.xeonmic.lbs.vo.POIUpDateCustomDate;
import com.xeonmic.lbs.vo.POIUpdateJson;
import com.xeonmic.lbs.vo.USERINFO;

/**
 * @author Xeon
 * @version 3.0
 */
public class LBSPoiDAOImpl implements LBSPoiDAO {

    /* (非 Javadoc)
     * @see com.xeonmic.lbs.dao.LBSPoiDAO#POICreate(com.xeonmic.lbs.vo.POICreateCustomDate)
     */
    @Override
    public POICreateJson POICreate(POICreateCustomDate poi) {
        // TODO 自动生成的方法存根
        String URL=LBSINFO.LBSPOIURL+"create";//post请求

        JSONObject node = null;
        try {
            node = JSONObject.fromObject(new HttpRequestor().doPost(URL, poi.toMap()));
        } catch (Exception e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        POICreateJson json =new POICreateJson(node.getInt("status"), node.getString("message") ,node.getString("id") );

        return json;
    }

    /* (非 Javadoc)
     * @see com.xeonmic.lbs.dao.LBSPoiDAO#POIFind(com.xeonmic.lbs.vo.POIFindObject)
     */
    @Override
    public POIFindJson POIFind(POIFindObject keys) {
        // TODO 自动生成的方法存根
        String URL=LBSINFO.LBSPOIURL+"list"+keys.toURL();//get请求
        System.out.println("URL="+URL);
        JSONObject node = null;
        POIFindJson json = null;
        try {
            node = JSONObject.fromObject(new HttpRequestor().doGet(URL));
        } catch (Exception e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        POI tPoi = null;
        List  poislist = new ArrayList();
        // JSONObject jsonPoi = node.getJSONObject("poi");
        json = new POIFindJson(node.getInt("status"), node.getString("message"), node.getInt("size"), node.getInt("total"), null);
        if (node.getInt("status")==0) {     
            JSONArray pois = node.getJSONArray("pois");
            for(int i=0;i
                JSONObject t =  pois.getJSONObject(i);
                JSONArray location = t.getJSONArray("location");            
                //System.out.println("zuobiao"+location.toString()+"i="+i);         
                Double Longitude=(Double) location.get(0);
                Double Latitude=(Double) location.get(1);           
                List locationList = new ArrayList<>();
                //System.out.println("Longitude="+Longitude);
                locationList.add(Longitude);
                locationList.add(Latitude);         
                //System.out.println(t.toString());         
                 tPoi=new POI(t.getInt("id"), locationList, t.getString("province"), t.getInt("city_id"), t.getString("city"),t.getString("district") ,t.getString("title") , t.getString("address"), 3, "", t.getString("geotable_id"), t.getString("create_time"), "");
                //System.out.println(tPoi.toString());
                 poislist.add(tPoi);
             }
            json.setPois(poislist);
        }else {
            System.out.println("status="+node.getInt("status"));
        }
        return json;
    }

    /* (非 Javadoc)
     * @see com.xeonmic.lbs.dao.LBSPoiDAO#POIFindById(int)
     */
    @Override
    public POIFindByIdJson POIFindById(int id) {
        // TODO 自动生成的方法存根
        String URL=LBSINFO.LBSPOIURL+"detail?ak="+USERINFO.ak+"&geotable_id="+USERINFO.geotable_id+"&id="+id;//get请求
        if(!"".equals(USERINFO.sn)){
            URL+="&sn="+USERINFO.sn;
        }
        System.out.println("URL="+URL);
        JSONObject node = null;
        POIFindByIdJson json = null;
        try {
            node = JSONObject.fromObject(new HttpRequestor().doGet(URL));
        } catch (Exception e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }

        // JSONObject jsonPoi = node.getJSONObject("poi");
        json = new POIFindByIdJson(node.getInt("status"), node.getString("message"), node.getInt("size"), node.getInt("total"), null);
        if (node.getInt("status")==0) {     
            JSONObject poi = node.getJSONObject("poi");
                JSONArray location = poi.getJSONArray("location");          
                //System.out.println("zuobiao"+location.toString()+"i="+i);         
                Double Longitude=(Double) location.get(0);
                Double Latitude=(Double) location.get(1);           
                List locationList = new ArrayList<>();
                //System.out.println("Longitude="+Longitude);
                locationList.add(Longitude);
                locationList.add(Latitude);         
                //System.out.println(t.toString());         
                 POI tPoi = new POI(poi.getInt("id"), locationList, poi.getString("province"), poi.getInt("city_id"), poi.getString("city"),poi.getString("district") ,poi.getString("title") , poi.getString("address"), 3, "", poi.getString("geotable_id"), poi.getString("create_time"), "");
                 json.setPoi(tPoi);


        }else {
            System.out.println("status="+node.getInt("status"));
        }
        return json;
    }

    /* (非 Javadoc)
     * @see com.xeonmic.lbs.dao.LBSPoiDAO#POIUpDate(com.xeonmic.lbs.vo.POIUpDateCustomDate)
     */
    @Override
    public POIUpdateJson POIUpDate(POIUpDateCustomDate poi) {
        // TODO 自动生成的方法存根
        String URL = LBSINFO.LBSPOIURL+"update";// POST请求]
        JSONObject node = null;
        try {
            node = JSONObject.fromObject(new HttpRequestor().doPost(URL, poi.toMap()));
        } catch (Exception e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        POIUpdateJson json = new POIUpdateJson(node.getInt("status"), node.getString("message"));
        return json;
    }

    /* (非 Javadoc)
     * @see com.xeonmic.lbs.dao.LBSPoiDAO#POIDelete(com.xeonmic.lbs.vo.POIDeleteObject)
     */
    @Override
    public POIDeleteJson POIDelete(POIDeleteObject poi) {
        // TODO 自动生成的方法存根
        String URL = LBSINFO.LBSPOIURL+"delete";// POST请求]
        JSONObject node = null;     
        String id="";
        try {
            node = JSONObject.fromObject(new HttpRequestor().doPost(URL, poi.toMap()));
        } catch (Exception e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        if(node.getInt("status")==0){
            id = node.getString("id");
        }       
        POIDeleteJson json = new POIDeleteJson(node.getInt("status"), node.getString("message"), id);
        return json;
    }

}

最后希望对那些和我一样在大学阶段想做关于百度地图方面项目的同学能有所帮助!

你可能感兴趣的:(百度地图API方向)