本帖最后由 ECGST 于 2024-11-12 14:42 编辑
转成Java
1. AK输入为自己申请的应用;
2. 请求检验方式设置为ip白名单的;(有空的话加上sn校验方式的)
3. 效果如图所示:
[Java] 纯文本查看 复制代码
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Slf4j
public class BaiduMapSearch {
private static final String SEARCH_URL = "http://api.map.baidu.com/place/v2/search";
private static final String DETAIL_URL = "http://api.map.baidu.com/place/v2/detail";
public static String AK = "";
private static final OkHttpClient CLIENT = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
public static void main(String[] args) throws UnsupportedEncodingException {
String keyword = "新丰小吃";
String region = "杭州市萧山区";
searchPlace(keyword, region);
}
public static void searchPlace(String keyword, String region) {
int pageNum = 0;
while (true) {
Map<String, String> searchParams = new LinkedHashMap<>();
searchParams.put("query", keyword);
searchParams.put("region", region);
searchParams.put("output", "json");
searchParams.put("ak", AK);
searchParams.put("page_num", String.valueOf(pageNum));
searchParams.put("page_size", "10");
String searchUrl = buildUrlWithParams(SEARCH_URL, searchParams);
try {
String responseData = executeRequest(searchUrl);
JSONObject jsonResponse = JSON.parseObject(responseData);
if (isResponseSuccessful(jsonResponse)) {
break;
}
JSONArray results = jsonResponse.getJSONArray("results");
if (results == null || results.isEmpty()) {
break;
}
for (int i = 0; i < results.size(); i++) {
JSONObject place = results.getJSONObject(i);
processPlace(place);
}
pageNum++;
} catch (IOException e) {
log.error("请求报错: {}", e.getMessage());
break;
}
}
}
private static String buildUrlWithParams(String baseUrl, Map<String, String> params) {
StringBuilder urlBuilder = new StringBuilder(baseUrl);
urlBuilder.append("?");
for (Map.Entry<String, String> entry : params.entrySet()) {
try {
urlBuilder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&");
} catch (Exception e) {
log.error("URL编码错误: {}", e.getMessage());
}
}
return urlBuilder.toString().substring(0, urlBuilder.length() - 1);
}
private static String executeRequest(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = CLIENT.newCall(request).execute()) {
if (!response.isSuccessful()) {
log.error("请求失败,状态码: {}", response.code());
return null;
}
return response.body().string();
}
}
private static boolean isResponseSuccessful(JSONObject jsonResponse) {
int status = jsonResponse.getIntValue("status");
if (status != 0) {
log.error("搜索请求失败,错误信息: {}", jsonResponse.getString("message"));
return true;
}
return false;
}
private static void processPlace(JSONObject place) {
String name = place.getString("name");
String address = place.getString("address");
JSONObject location = place.getJSONObject("location");
double lat = location.getDoubleValue("lat");
double lng = location.getDoubleValue("lng");
String uid = place.getString("uid");
String detailUrl = String.format("%s?uid=%s&output=json&scope=2&ak=%s", DETAIL_URL, uid, AK);
try {
String detailResponseData = executeRequest(detailUrl);
if (detailResponseData == null) {
return;
}
JSONObject detailJsonResponse = JSON.parseObject(detailResponseData);
if (isResponseSuccessful(detailJsonResponse)) {
return;
}
JSONObject detailResult = detailJsonResponse.getJSONObject("result");
String telephone = detailResult.getString("telephone");
log.info("名称: {}", name);
log.info("地址: {}", address);
log.info("经度: {}", lng);
log.info("纬度: {}", lat);
log.info("联系方式: {}", telephone);
log.info("--------------------------------------------");
} catch (IOException e) {
log.error("请求报错: {}", e.getMessage());
}
}
}
|