题目:
注册百度开发者http://lbsyun.baidu.com/
使用WEB 服务API,具体方法如下
http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-placeapi
发送get请求获取,响应信息
http://api.map.baidu.com/place/v2/search?query=银行&bounds=39.915,116.404,39.975,116.414&output=json&ak=你的ak
1.以正则方式提取响应中第一条信息的lat 和lng的坐标值
2.利用json解析响应获取lat 和lng的坐标值(考虑使用org.json.simple)
答案:
1.注册百度开发者
package com.my.homework0315;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Request;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class FluentGet {
public static String getRequest() {
String text = null;
try {
text = Request.Get("http://api.map.baidu.com/place/v2/search?query=银行&bounds=39.915,116.404,39.975,116.414&output=json&ak=IGZGHi0N2hhgjhnPThX6Wq073wvLEl8s")
.execute().returnContent().asString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return text;
}
public static void regularFunc(String text) {
Pattern p1 = Pattern.compile("\"lat\":(.*),");
Matcher m1 = p1.matcher(text);
if(m1.find()) {
System.out.println("lat:"+m1.group(1));
}
Pattern p2 = Pattern.compile("\"lng\":(.*)");
Matcher m2 = p2.matcher(text);
if(m2.find()) {
System.out.println("lng:"+m2.group(1));
}
}
public static void jsonFunc(String text) {
JSONObject jsonobj=(JSONObject) JSONValue.parse(text);
System.out.println(jsonobj);
JSONArray jsonArr = (JSONArray) jsonobj.get("results");
System.out.println(jsonArr);
JSONObject value = (JSONObject) jsonArr.get(0);
System.out.println(value);
JSONObject location = (JSONObject) value.get("location");
System.out.println(location);
String lng = location.get("lng").toString();
System.out.println("lng:"+lng);
String lat = location.get("lat").toString();
System.out.println("lat:"+lat);
}
}
package com.my.homework0315;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Request;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class FluentGetTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test1() {
String text = FluentGet.getRequest();
System.out.println("====================");
System.out.println("test1");
FluentGet.regularFunc(text);
}
@Test
public void test2() {
String text = FluentGet.getRequest();
System.out.println("====================");
System.out.println("test2");
FluentGet.jsonFunc(text);
}
}
运行结果: