功能代码

httpclient方式请求百度的转换地址
http://api.map.baidu.com/ag/coord/convert?from=2&to=4&x=&y=
拿到的是转换后的json数据,但是坐标值是base64加密过的字符,需要解密一下

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;

public class BaiduMapUtils {

public static final String googleToBaiduUrl = "http://api.map.baidu.com/ag/coord/convert?from=2&to=4&x=#x#&y=#y#";

public static String httpClientForGet(String url){
HttpClient client = new HttpClient();
GetMethod getMethod = new GetMethod(url);
getMethod.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");

try {
client.executeMethod(getMethod);
if (getMethod.getStatusCode() == HttpStatus.SC_OK) {
return getMethod.getResponseBodyAsString();
}
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
getMethod.releaseConnection();
}
return "";
}

/**
* 转换谷歌为百度坐标
* @param x 经度
* @param y 纬度
* @return 获取转换过的百度坐标
*/
public static Map<String, Object> googleToBaidu(Double x, Double y){
Map<String, Object> map = new HashMap<String, Object>();

String relt = httpClientForGet(getGoogleToBaiduUrl(String.valueOf(x), String.valueOf(y)));
if(DyString.isNotEmpty(relt))
map = JsonUtils.parserToMap(relt);

map.put("x", Base64Utils.decode(map.get("x")));
map.put("y", Base64Utils.decode(map.get("y")));

return map;
}

/**
* 获取请求地址
*
* @param x
* @param y
* @return
*/
public static String getGoogleToBaiduUrl(String x, String y){
return googleToBaiduUrl.replace("#x#", x).replace("#y#", y);
}

/**
* URL中文字符编码
* @param url
* @return
*/
public static String encode(String s){
return URLEncoder.encode(s);
}

public static void main(String[] args) {
System.out.println(googleToBaidu(31.2306192233586, 121.446663737297));
}
}

Base64Utils

使用apache的commons包下面的base64工具类

import org.apache.commons.codec.binary.Base64;

/**
* base64加密解密工具 使用apache工具包
*
* @author 刘兴
*
*/
public class Base64Utils {

/**
* base64加密字符串
*
* @param s
* @return
*/
public static String encode(Object s) {
if (s == null)
return null;
Base64 base64 = new Base64();
byte[] enbytes = base64.encode(String.valueOf(s).getBytes());
return new String(enbytes);
}

/**
* base64解密字符串
*
* @param s
* @return
*/
public static String decode(Object s) {
if (s == null)
return null;
Base64 base64 = new Base64();
byte[] debytes = base64.decode(String.valueOf(s).getBytes());
return new String(debytes);
}

public static void main(String[] a) {
System.out.println(Base64Utils.decode("MTE2LjI2MTA5OTEyMjE="));
}
}

DyString类是一个自定义的字符串处理工具类,可以调用apache的工具类StringUtils.isEmpty或isNotEmpty
JsonUtils类是自定义的json字符串处理工具类,内部功能是将json字符串转换成map对象