package com.mbyte.easy.util;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName GetPhoneLocationUtil
* @Description 根据手机号码查询出归属地
* @Author 戴书博
* @Date 2019/11/4 15:19
* @Version 1.0
**/
@Slf4j
public class GetPhoneLocationUtil {
/**
* @Method getJson
* @Author 戴书博
* @Description 查询号码的归属地
* @param phone
* @Return java.util.Map<java.lang.String,java.lang.String>
* @Date 2019/11/4 15:23
* @Version 1.0
*/
public static String getLocation(String phone){
String url = "https://cx.shouji.360.cn/phonearea.php?number="+phone;
String jsonStr = GetPhoneLocationUtil.getJson(url);
log.info("jsonStr => {}",jsonStr);
JSONObject jsonObject = JSONObject.parseObject(jsonStr).getJSONObject("data");
// String province = jsonObject.get("province").toString();
String city = jsonObject.get("city").toString();
// String sp = jsonObject.get("sp").toString();
// Map<String,String> map = new HashMap<>();
// map.put("province",province);
// map.put("city",city);
// log.info("map => {}",map);
return city;
}
/**
* @Method getLocation
* @Author 戴书博
* @Description 访问外部接口,获取json
* @param url
* @Return java.lang.String
* @Date 2019/11/4 15:20
* @Version 1.0
*/
public static String getJson(String url){
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
//获取HttpClient对象
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
//创建httpGet请求对象,设置url
HttpGet httpGet = new HttpGet(url);
//设置请求Request Headers中的User-Agent
httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36");
CloseableHttpResponse response = null;
//设置请求信息
try {
response = httpClient.execute(httpGet);
//判断响应,返回结果
if(response.getStatusLine().getStatusCode() == 200){
//判断响应体Entity是否为空,如果不为空就可以使用EmtityUtils
if(response.getEntity() != null){
String content = EntityUtils.toString(response.getEntity(),"utf-8");
return content;
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if (response != null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "";
}
}