java根据经纬度获取地址

/**
* @Title: getCity
* @Description: TODO(根据经纬度获取地址 调用百度地图)
* @date 2021年4月12日 下午2:04:21
* @param lat 纬度
* @param lng 经度
* @return
* @throws
*/
public String getAddress(String lat, String lng) {
net.sf.json.JSONObject obj = getLocationInfo(lat, lng).getJSONObject(“result”);
String address = obj.getString(“formatted_address”);
return address;
}
public net.sf.json.JSONObject getLocationInfo(String lat, String lng) {
String url = “http://api.map.baidu.com/geocoder/v2/?location=” + lat + “,”
+ lng + “&output=json&ak=XsilXlH0tREQPUujz7aGDLsVkWdz1YO9&pois=0”;
net.sf.json.JSONObject obj = net.sf.json.JSONObject.fromObject(HttpUtil.getRequest(url));
return obj;
}

package com.jrfmail.core.web.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtil {
// 连接超时时间
private static final int CONNECTION_TIMEOUT = 3000;
//读取超时时间
private static final int READ_TIMEOUT = 5000;
// 参数编码
private static final String ENCODE_CHARSET = “utf-8”;

public static String postRequest(String reqURL, String... params) {
	StringBuilder resultData = new StringBuilder();
	URL url = null;
	try {

		url = new URL(reqURL);
	} catch (MalformedURLException e) {
		e.printStackTrace();
	}
	HttpURLConnection urlConn = null;
	InputStreamReader in = null;
	BufferedReader buffer = null;
	String inputLine = null;
	DataOutputStream out = null;
	if (url != null) {
		try {
			urlConn = (HttpURLConnection) url.openConnection();
			urlConn.setDoInput(true);// 设置输入流采用字节流
			urlConn.setDoOutput(true);// 设置输出流采用字节流
			urlConn.setRequestMethod("POST");
			urlConn.setUseCaches(false); // POST请求不能使用缓存
			urlConn.setInstanceFollowRedirects(true);
			urlConn.setConnectTimeout(CONNECTION_TIMEOUT);// 设置连接超时
			urlConn.setReadTimeout(READ_TIMEOUT); // 设置读取超时
			// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
			urlConn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			urlConn.setRequestProperty("Charset", ENCODE_CHARSET);//
			String param = sendPostParams(params);
			urlConn.setRequestProperty("Content-Length",
					param.getBytes().length + "");//
			// urlConn.setRequestProperty("Connection", "Keep-Alive");
			// //设置长连接
			urlConn.connect();// 连接服务器发送消息
			if (!"".equals(param)) {
				out = new DataOutputStream(urlConn.getOutputStream());
				// 将要上传的内容写入流中
				out.writeBytes(param);
				// 刷新、关闭
				out.flush();
				out.close();

			}
			in = new InputStreamReader(urlConn.getInputStream(),
					HttpUtil.ENCODE_CHARSET);
			buffer = new BufferedReader(in);
			if (urlConn.getResponseCode() == 200) {
				while ((inputLine = buffer.readLine()) != null) {
					resultData.append(inputLine);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (buffer != null) {
					buffer.close();
				}

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

				if (urlConn != null) {
					urlConn.disconnect();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	return resultData.toString();
}

/**
 * 发送HTTP_GET请求
 * 
 * @see 本方法默认的连接和读取超时均为30秒
 * @param httpUrl
 *            请求地址
 * @param map
 *            发送到远程主机的正文数据[a:1,b:2]
 * @return String
 */
public static String getRequest(String httpUrl, String... params) {
	StringBuilder resultData = new StringBuilder();
	URL url = null;
	try {

		String paramurl = sendGetParams(httpUrl, params);
		url = new URL(paramurl);

	} catch (MalformedURLException e) {
		e.printStackTrace();
	}
	HttpURLConnection urlConn = null;
	InputStreamReader in = null;
	BufferedReader buffer = null;
	String inputLine = null;
	if (url != null) {
		try {
			urlConn = (HttpURLConnection) url.openConnection();
			urlConn.setRequestMethod("GET");
			urlConn.setConnectTimeout(CONNECTION_TIMEOUT);
			in = new InputStreamReader(urlConn.getInputStream(),
					HttpUtil.ENCODE_CHARSET);
			buffer = new BufferedReader(in);
			if (urlConn.getResponseCode() == 200) {
				while ((inputLine = buffer.readLine()) != null) {
					resultData.append(inputLine);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (buffer != null) {
					buffer.close();
				}

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

				if (urlConn != null) {
					urlConn.disconnect();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	return resultData.toString();
}

/**
 * Post追加参数
 * 
 * @see <code>params</code>
 * @param reqURL
 *            请求地址
 * @param params
 *            发送到远程主机的正文数据[a:1,b:2]
 * @return
 */
private static String sendPostParams(String... params) {
	StringBuilder sbd = new StringBuilder("");
	if (params != null && params.length > 0) {
		for (int i = 0; i < params.length; i++) {
			String[] temp = params[i].split(":");
			sbd.append(temp[0]);
			sbd.append("=");
			sbd.append(urlEncode(temp[1]));
			sbd.append("&");

		}
		sbd.setLength(sbd.length() - 1);// 删掉最后一个
	}
	return sbd.toString();
}

/**
 * Get追加参数
 * 
 * @see <code>params</code>
 * @param reqURL
 *            请求地址
 * @param params
 *            发送到远程主机的正文数据[a:1,b:2]
 * @return
 */
private static String sendGetParams(String reqURL, String... params) {
	StringBuilder sbd = new StringBuilder(reqURL);
	if (params != null && params.length > 0) {
		if (isexist(reqURL, "?")) {// 存在?
			sbd.append("&");
		} else {
			sbd.append("?");
		}
		for (int i = 0; i < params.length; i++) {
			String[] temp = params[i].split(":");
			sbd.append(temp[0]);
			sbd.append("=");
			sbd.append(urlEncode(temp[1]));
			sbd.append("&");

		}
		sbd.setLength(sbd.length() - 1);// 删掉最后一个
	}
	return sbd.toString();
}

// 查找某个字符串是否存在
private static boolean isexist(String str, String fstr) {
	return str.indexOf(fstr) == -1 ? false : true;
}

/**
 * 编码
 * 
 * @param source
 * @return
 */
private static String urlEncode(String source) {
	String result = source;
	try {
		result = java.net.URLEncoder
				.encode(source, HttpUtil.ENCODE_CHARSET);
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
	return result;
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值