首先根据官方文档:谷歌地图API网络服务,通过浏览器:http://ditu.google.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false&&language=zh-CN,得到返回的数据是:
{
"status": "OK",
"results": [ {
"types": [ "street_address" ],
"formatted_address": "279-281 貝德福大街, 布魯克林, 紐約 11211, 美國",
"address_components": [ {
"long_name": "279-281",
"short_name": "279-281",
"types": [ "street_number" ]
}, {
"long_name": "貝德福大街",
"short_name": "貝德福大街",
"types": [ "route" ]
}, {
"long_name": "布魯克林",
"short_name": "布魯克林",
"types": [ "sublocality", "political" ]
}, {
"long_name": "紐約",
"short_name": "紐約",
"types": [ "locality", "political" ]
}, {
"long_name": "京斯",
"short_name": "京斯",
"types": [ "administrative_area_level_2", "political" ]
}, {
"long_name": "紐約",
"short_name": "NY",
"types": [ "administrative_area_level_1", "political" ]
}, {
"long_name": "美國",
"short_name": "US",
"types": [ "country", "political" ]
}, {
"long_name": "11211",
"short_name": "11211",
"types": [ "postal_code" ]
} ],
"geometry": {
"location": {
"lat": 40.7142215,
"lng": -73.9614454
},
"location_type": "RANGE_INTERPOLATED",
"viewport": {
"southwest": {
"lat": 40.7110552,
"lng": -73.9646313
},
"northeast": {
"lat": 40.7173505,
"lng": -73.9583361
}
},
"bounds": {
"southwest": {
"lat": 40.7139010,
"lng": -73.9616800
},
"northeast": {
"lat": 40.7145047,
"lng": -73.9612874
}
}
}
}
需要利用程序分析返回的结果,打算利用java模拟http请求,得到返回的数据。代码片段如下:
pom文件中引入必要的jar包:
<dependency>
<groupId>commons-httpclient</groupId><artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
java代码片段:
private static HttpMethod getGetMethod() throws IOException {
GetMethod get = new GetMethod("/maps/api/geocode/json");NameValuePair simcard = new NameValuePair("latlng", "40.714224,-73.961452");
NameValuePair simcard1 = new NameValuePair("sensor", "false");
NameValuePair simcard2 = new NameValuePair("language", "zh-CN");
get.setQueryString(new NameValuePair[] { simcard, simcard1,simcard2});
//InputStream input = new FileInputStream(new File("/home/ubuntu/my.txt"));
//"".getBytes("ISO8859-1")
//InputStream input = new StringBufferInputStream("my test aaaaaaaaaa");
//post.setRequestBody(input);
return get;
}
public static void main(String[] args) throws IOException {
HttpClient client = new HttpClient();client.getHostConfiguration().setHost("ditu.google.com", 80, "http");
HttpMethod method = getGetMethod();// 使用GET方式提交数据
client.executeMethod(method);
// 打印服务器返回的状态
System.out.println(method.getStatusLine());
// 打印结果页面
;
//
try {BufferedReader rd = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(),
"UTF-8"));
StringBuffer sb = new StringBuffer();
String line;while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();System.out.println("接受到的流是:" + sb);
} catch (IOException e) {
throw new RuntimeException("error", e);
}
method.releaseConnection();
}
完整代码见:http://bigcateasymorse.googlecode.com/svn/trunk/GoogleMapCoding/
