邮编查询

pull/1/head
chaiyapeng 2024-08-24 20:53:53 +08:00
parent cbb34dca72
commit 7e5ce7d137
1 changed files with 59 additions and 0 deletions

View File

@ -0,0 +1,59 @@
package com.muyu.cloud.mart.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @Authorchaiyapeng
* @Packagecom.muyu.cloud.mart.utils
* @Projectcloud-mart
* @namePostcode
* @Date2024/8/24 20:50
*/
public class PostcodeInquire {
public static StringBuffer queryPostcode(){
String apiKey = "0cabcd31c150369d8afb2c8b7e41a2c0";
String apiUrl = "http://v.juhe.cn/postcode/query";
HashMap<String, String> map = new HashMap<>();
map.put("key", apiKey);
map.put("postcode", "xxx");
map.put("page", "20");
map.put("pagesize", "");
map.put("dtype", "json");
try {
URL url = new URL(String.format(apiUrl + "?" + params(map)));
BufferedReader in = new BufferedReader(new InputStreamReader((url.openConnection()).getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response);
return response;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String params(Map<String, String> map) {
return map.entrySet().stream()
.map(entry -> {
try {
return entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString());
} catch (Exception e) {
e.printStackTrace();
return entry.getKey() + "=" + entry.getValue();
}
})
.collect(Collectors.joining("&"));
}
}