import com.alibaba.fastjson.*
import ……
// coords: '114.21892734521,29.575429778924'
// return: ['114.2307519546763', '29.57908428837437']
// 可以传入多个点,详见 https://lbsyun.baidu.com/faq/api?title=webapi/guide/changeposition-base#%E7%A4%BA%E4%BE%8B%E4%BB%A3%E7%A0%81
public static String[] transCoords(String coords) throws Exception {
String ak = "***";
String dest_url = "http://api.map.baidu.com/geoconv/v1/?coords=" + coords + "&from=1&to=5&output=json&ak=" + ak;
String commString = "";
String rec_string = "";
URL url = null;
HttpURLConnection urlconn = null;
OutputStream out = null;
BufferedReader rd = null;
try {
url = new URL(dest_url);
urlconn = (HttpURLConnection) url.openConnection();
urlconn.setReadTimeout(1000 * 30);
// urlconn.setRequestProperty("content-type", "text/html;charset=UTF-8");
urlconn.setRequestMethod("POST");
urlconn.setDoInput(true);
urlconn.setDoOutput(true);
out = urlconn.getOutputStream();
out.write(commString.getBytes("UTF-8"));
out.flush();
out.close();
rd = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
StringBuffer sb = new StringBuffer();
int ch;
while ((ch = rd.read()) > -1)
sb.append((char) ch);
rec_string = sb.toString();
} catch (Exception e) {
} finally {
try {
if (out != null) {
out.close();
}
if (urlconn != null) {
urlconn.disconnect();
}
if (rd != null) {
rd.close();
}
} catch (Exception e) {
}
}
JSONObject res = JSONObject.parseObject(rec_string).getJSONArray("result").getJSONObject(0);
return new String[]{res.getString("x"), res.getString("y")};
}
标签:JAVA,String,rd,API,urlconn,new,null,百度,out
From: https://www.cnblogs.com/xhltk316/p/17525677.html