调用google地图接口 的封装

示例:

package com.destination.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.destination.LocationReq;
import com.sms.http.SmsAuth;
import com.weibo.weibo4j.model.MySSLSocketFactory;

public class DestinationMsg
{
    static Log log = LogFactory.getLog(DestinationMsg.class);
    private static final String authCode = "25192bd58726e1e0dd59efac686e5daeb5273b46";

    /** 设置消息头、参数
     * 
     * @param message
     *            短息信息
     * @param URL
     *            请求的URL
     * @return 是否成功
     * @exception Exception */
    public JSONObject httpGetRequest(LocationReq message, String URL, String appKey, String token)
    {
        String authorization = "appKey=" + '"' + appKey + '"' + ",token=" + '"' + token + '"';
        // String authorization = "appKey=" + '"' + appKey + '"' + ",token=" + '"' + token + '"';
        JSONObject jsonResult = null;

        Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
        Protocol.registerProtocol("https", myhttps);

        // 定义http客户端对象--httpClient
        HttpClient httpClient = new HttpClient();
        // 定义并实例化客户端链接对象-GetMethod
        GetMethod postMethod = new GetMethod(URL);

        // 设置http的头
        postMethod.setRequestHeader("Authorization", authorization);
        postMethod.setRequestHeader("Content-Type", "application/json;charset=utf-8");
        postMethod.setRequestHeader("Accept", "application/json");
        jsonResult = httpRequest(httpClient, postMethod);

        return jsonResult;
    }

    /** 根据经纬度反向解析地址,有时需要多尝试几次 注意:(摘自:http://code.google.com/intl/zh-CN/apis/maps/faq.html 提交的地址解析请求次数是否有限制?) 如果在 24
     * 小时时段内收到来自一个 IP 地址超过 15,000 个地址解析请求, 或从一个 IP 地址提交的地址解析请求速率过快,Google 地图 API 编码器将用 620 状态代码开始响应。 如果地址解析器的使用仍然过多,则从该
     * IP 地址对 Google 地图 API 地址解析器的访问可能被永久阻止。
     * 
     * @param latitude
     *            纬度
     * @param longitude
     *            经度
     * @return */
    public static String geocodeAddr(String latitude, String longitude)
    {
        String addr = "";

        // 也可以是http://maps.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s,不过解析出来的是英文地址
        // 密钥可以随便写一个key=abc
        // output=csv,也可以是xml或json,不过使用csv返回的数据最简洁方便解析
        String url = String.format("http://ditu.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s", latitude, longitude);
        URL myURL = null;
        URLConnection httpsConn = null;
        try
        {
            myURL = new URL(url);
        }
        catch (MalformedURLException e)
        {
            log.error("请求URL地址失败!", e);
            return null;
        }
        try
        {
            httpsConn = (URLConnection) myURL.openConnection();
            if (httpsConn != null)
            {
                InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
                BufferedReader br = new BufferedReader(insr);
                String data = null;
                if ((data = br.readLine()) != null)
                {
                    System.out.println(data);
                    String[] retList = data.split(",");
                    if (retList.length > 2 && ("200".equals(retList[0])))
                    {
                        addr = retList[2];
                        addr = addr.replace("\"", "");
                    }
                    else
                    {
                        addr = "";
                    }
                }
                insr.close();
            }
        }
        catch (IOException e)
        {
            log.error("获取请求响应结果失败!", e);
            return null;
        }
        return addr;

    }

    /** 请求发送
     * 
     * @param HttpClient
     * @param PostMethod
     * @param JSONObject
     * @return 是否成功
     * @exception Exception */
    public JSONObject httpRequest(HttpClient httpClient, GetMethod postMethod)
    {
        // 解析响应结果
        JSONObject jsonResult = new JSONObject();
        // 响应内容
        String result = "";
        try
        {
            log.info("httpClient编码格式:----------->" + postMethod.getRequestCharSet());
            // 定义访问地址的链接状态
            int statusCode = 0;
            try
            {
                // 客户端请求url数据
                statusCode = httpClient.executeMethod(postMethod);
            }
            catch (Exception e)
            {
                log.error("请求URL失败!", e);
                return jsonResult;
            }

            // 请求成功状态-200
            if (statusCode == HttpStatus.SC_OK)
            {
                try
                {
                    // 获取请求响应结果
                    result = postMethod.getResponseBodyAsString();
                    log.info("result----------->" + result);
                }
                catch (IOException e)
                {
                    log.error("获取请求响应结果失败!", e);
                    return jsonResult;
                }
            }
            else
            {
                log.error("访问地址请求失败!:" + statusCode);
                return jsonResult;
            }
        }
        catch (Exception e)
        {
            log.error(e.getMessage(), e);
            return jsonResult;
        }
        finally
        {
            // 释放链接
            postMethod.releaseConnection();
            httpClient.getHttpConnectionManager().closeIdleConnections(0);
        }

        try
        {
            jsonResult = JSONObject.fromObject(result);
        }
        catch (JSONException e)
        {
            log.error("获取的Http响应结果格式错误!", e);

        }

        return jsonResult;
    }
}

转载于:https://my.oschina.net/u/1172409/blog/155702

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一个老外(西班牙)编写的控件,封装了全部google maps api ,使用在DELPHI中使用谷歌地图变得非常简单 GMLib - Google Maps Library Send suggestions to gmlib@cadetill.com Supported Delphi version: Delphi 6, 7, 2007, 2010, XE2, XE3 Tested Windows Versions: XP, 2003, Vista, 7 Change History january 14, 2013 - Google Maps Library v0.1.9 - Improvement: Compatible with FMX framework. - Improvement: About all Geometry Library coded. - bug fixed: Some bugs fixes. - Attempt to do compatible with DCEF components. October 05, 2012 - Google Maps Library v0.1.8 - Improvement: Compiled under XE3 - Improvement: new component added, the TGMElevation. - bug fixed: General -> fixed all memory leaks found - bug fixed: TGMDirection -> the OnDirectionsChanged event was not triggered - Improvement: TBasePolyline -> class TLinePoints and TLinePoint is disassociated from TPolyline and they are transferred to GMClasses - Improvement: TBasePolyline -> implements ILinePoint interface September 11, 2012 - Google Maps Library v0.1.7 - bug fixed: some memory leaks fixed (there is still some) (thanks Donovan) - Improvement: TGMCircle -> modified all Set and ShowElements methods to use the new method ChangeProperties inherited from TLinkedComponent - Improvement: GMFunctions -> added new functions of transformation types - Improvement: TGMGeoCode-> added boolean property PaintMarkerFound. To true, all markers are automatically generated (if a TGMMarker is linked) (by Luis Joaquin Sencion) - Improvement: TGMGeoCode-> generated URL is encoded in UTF8 to avoid problems with special characters (? accents, ....) - Improvement: TGMMap.TNonVisualProp -> added MapMarker property. True if Map Maker tiles should be used instead of regular tiles. - Improvement: TLatLngEvent -> the events of this type now have a new parametre, X and Y, of Real type, with information of point (X,Y) - Improvement: TLinkedComponent -> added ShowInfoWinMouseOver boolean property. If true, show the InfoWindows when mouse is over the object. Now

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值