我正在开发Google,用下面的代码片段进行反向地理编码。
我所用的是:
它工作得很好,但效果有点慢。我能提高我的代码的性能吗?
package com.addressparser.api;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class GeocodeAddressParser {
public String getLocationInfo( String lat, String lng) throws JsonProcessingException, IOException {
HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=false");
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
ObjectMapper mapper = new ObjectMapper();
JsonNode array = mapper.readValue(stringBuilder.toString(), JsonNode.class);
JsonNode object = array.get("results").get(0);
String reportKey = object.get("formatted_address").textValue();
System.out.println(reportKey);//just printing it on the console for testing at the moment
return reportKey;
}
public static void main(String[] args) throws JsonProcessingException, IOException{
GeocodeAddressParser ref = new GeocodeAddressParser();
ref.getLocationInfo("31.338451","75.554183");
}
}发布于 2017-07-27 21:52:36
永远不要像这样默默地吞下例外:
} catch (ClientProtocolException e) {} catch (IOException e) {}
因此,调试隐藏的问题需要花费大量的时间。至少,将一些诊断消息打印到System.err。此外,您无法负责任地继续尝试解析一个不完整的结果,因此您应该中止处理。
基本上,如果您不知道如何处理异常,您可能应该传播它。事实上,您已经声明getLocationInfo()可以抛出一个IOException,那么为什么要费心捕捉IOException呢?
发布于 2018-07-24 14:09:13
因为这是一个旧的帖子,只是一些简短的评论:
InputStream读入StringBuilder。杰克逊的ObjectMapper#readValue可以直接从InputStream中读取。JsonNode#path(String)和JsonNode#path(int)而不是get来避免获取null和NullPointerException。编辑:最后一件事:既然您正在使用Spring,那么请看一看RestTemplate。它在一个步骤中使用Jackson执行HTTP请求和JSON解析:
ObjectNode result = restTemplate.getForObject("http://maps.google.com/maps/api/geocode/json?latlng={latlang}&sensor=false", ObjectNode.class, lat+","+lng);
JsonNode object = result.get("results").get(0);
// etc.https://codereview.stackexchange.com/questions/171343
复制相似问题