【发布时间】:2016-12-06 09:05:20
【问题描述】:
我有一个从 url 中提取数据的 JAVA 程序。
提取.java
public class Uni_Extract {
protected static String lat;
protected static String lng;
public static void main(String[] args) throws Exception {
System.out.println("Started");
String csvFile = "C://Users/Kennedy/Desktop/university.csv";
FileWriter writer = new FileWriter(csvFile);
for (int i=2; i<=2; i++){
String url = "http://www.4icu.org/reviews/index"+i+".htm";
Document doc = Jsoup.connect(url).userAgent("Mozilla").get();
Elements cells = doc.select("td.i");
Iterator<Element> iterator = cells.iterator();
while (iterator.hasNext()) {
Element cell = iterator.next();
String university = Jsoup.parse((cell.select("a").text())).text();
String country = cell.nextElementSibling().select("img").attr("alt");
LatLngBackup LatLngBackup = new LatLngBackup();
LatLngBackup.getLatLongPositions(university);
System.out.print(university);
System.out.printf(", lat : %s, lng : %s %n", lat, lng);
CSVUtils.writeLine(writer,Arrays.asList(country,university,lat,lng),',','"');
}
}
writer.flush();
writer.close();
}
}
然后我还调用了一个java类LatLng从谷歌地图api中调用经纬度。
public class LatLngBackup extends Uni_Extract
{
public String[] getLatLongPositions(String address) throws Exception
{
int responseCode = 0;
String api = "https://maps.googleapis.com/maps/api/place/textsearch/xml?query=" + URLEncoder.encode(address, "UTF-8") +
"&key=AIzaSyCTBvomwAMvq0pSxgN0y2I_wALFJ8cx57Y";
URL url = new URL(api);
HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection();
httpConnection.connect();
responseCode = httpConnection.getResponseCode();
if(responseCode == 200)
{
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();;
Document document = builder.parse(httpConnection.getInputStream());
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/PlaceSearchResponse/status");
String status = (String)expr.evaluate(document, XPathConstants.STRING);
if(status.equals("OK"))
{
expr = xpath.compile("//geometry/location/lat");
super.lat = (String)expr.evaluate(document, XPathConstants.STRING);
expr = xpath.compile("//geometry/location/lng");
super.lng = (String)expr.evaluate(document, XPathConstants.STRING);
return new String[] {lat, lng};
}
else
{
super.lat="";
super.lng="";
}
}
return null;
}
}
但是,它给了我达到 API 密钥请求限制的消息。有没有其他方法可以做到这一点?
【问题讨论】:
-
也许您应该使用例如 sigleton 来防止每次调用此函数时建立连接。当然,您应该阅读一些有关 OOP 的内容。
-
付费订阅谷歌服务,这样你就可以请求所有你需要的数据。免费 API KEY 用于开发目的,并且有请求限制。
-
@shutdown-hnow 请你解释一下。我不擅长使用 Google Map API 和 JAVA
-
@KennedyKan 这是一个使用限制的问题,而不是真正的代码。
标签: java html api google-maps