关键代码:使用淘宝提供的接口,使用JsonPath解析JSON字符串
public String getProvideByPhoneNum( String phoneNum){
String province = null;
try {
String url = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel="+phoneNum;
String s = HttpUtils.doGet(url.trim());
s = s.replace("__GetZoneResult_ = ","");
province = JsonPath.parse(s).read("$.province");
} catch (Exception e) {
e.printStackTrace();
}
return province;
}
http请求工具类,使用HttpClient工具类
public class HttpUtils {
private static final Logger LOG = LoggerFactory.getLogger(HttpUtils.class);
public static String Curl(String PostUrl, String[] Parameters) throws Exception {
if (null == PostUrl || null == Parameters || Parameters.length == 0) {
return null;
}
String result = "";
PrintWriter out = null;
BufferedReader in = null;
try {
//建立URL之间的连接
URLConnection conn = new URL(PostUrl).openConnection();
//设置通用的请求属性
conn.setRequestProperty("Host", "data.zz.baidu.com");
conn.setRequestProperty("User-Agent", "curl/7.12.1");
conn.setRequestProperty("Content-Length", "83");
conn.setRequestProperty("Content-Type", "text/plain");
//发送POST请求必须设置如下两行
conn.setDoInput(true);
conn.setDoOutput(true);
//获取conn对应的输出流
out = new PrintWriter(conn.getOutputStream());
//发送请求参数
String param = "";
for (String s : Parameters) {
param += s + "\n";
}
out.print(param.trim());
//进行输出流的缓冲
out.flush();
//通过BufferedReader输入流来读取Url的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送post请求出现异常!" + e);
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* 普通POST请求
*
* @param url
* @param jsonFormString
* @return
* @throws Exception
*/
public static JSONObject doPost(String url, String jsonFormString) throws Exception {
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.addHeader("text/plain", "UTF-8");
post.addHeader("Content-Type", "application/json");
LOG.info("POST请求内容:{}", jsonFormString);
StringEntity s = new StringEntity(jsonFormString, Charsets.UTF_8);
post.setEntity(s);
return executePost(post, client);
}
/**
* 以form方式请求post
*
* @param url
* @param map
* @return
* @throws Exception
*/
public static JSONObject doPostToForm(String url, Map<String, String> map) throws Exception {
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.addHeader("text/plain", "UTF-8");
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
Set<String> keySet = map.keySet();
for (String key : keySet) {
pairList.add(new BasicNameValuePair(key, map.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
return executePost(post, client);
}
/**
* GET方式请求
*
* @param url
* @return
* @throws Exception
*/
public static String doGet(String url) throws Exception {
HttpClient client = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
get.setHeader("Content-Type", "application/json; charset=UTF-8");
String response = null;
HttpResponse httpResponse = client.execute(get);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
response = EntityUtils.toString(httpResponse.getEntity());// 返回json格式:
} else {
String errorMsg = EntityUtils.toString(httpResponse.getEntity());
throw new RuntimeException(errorMsg);
}
return response;
}
public static String HttpUrlGet(String url) throws IOException {
URL u = new URL(url);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
con.connect();
String result = "";
if (con.getResponseCode() == HttpStatus.SC_OK) {
InputStream in = con.getInputStream();
BufferedReader buff = new BufferedReader(new InputStreamReader(in, "utf-8"));
String line = null;
while ((line = buff.readLine()) != null) {
result += line + "\n";
}
in.close();
buff.close();
} else {
result = "请求错误";
}
return result;
}
/**
* 执行post请求
*
* @param post
* @param client
* @return
* @throws IOException
*/
private static JSONObject executePost(HttpPost post, HttpClient client) throws IOException {
HttpResponse httpResponse = client.execute(post);
JSONObject response = null;
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(httpResponse.getEntity());// 返回json格式:
LOG.info("result的内容: {}", result);
response = JSONObject.parseObject(result);
} else {
String errorMsg = EntityUtils.toString(httpResponse.getEntity());
throw new RuntimeException(errorMsg);
}
return response;
}
/**
* 带参数的get请求
*
* @param url
* @param params
* @return
*/
public static String doGetWhitParams(String url, List<NameValuePair> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String result = "";
String urlEntity = "";
try {
//转换为键值对
urlEntity = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
//创建get请求
HttpGet get = new HttpGet(url + "?" + urlEntity);
//执行get请求
response = httpClient.execute(get);
//得到响应体
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
} finally {
//消耗实体内容
if (null != response) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭相应 丢弃http连接
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* post请求发送form-data
*
* @param url
* @param filePath
* @return
*/
public static String doPostWhitFile(String url, String filePath) {
String result = null;
CloseableHttpResponse httpResponse = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
File file = new File(filePath);
if (file == null || !file.exists()) {
throw new FileNotFoundException();
}
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addBinaryBody("media", file).setMode(HttpMultipartMode.RFC6532);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(multipartEntityBuilder.build());
httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != httpResponse) {
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* post 发送json数据
* @param url
* @param strJson
* @return
*/
public static String doPostWhitJson(String url, String strJson) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String result = "";
HttpPost post = new HttpPost(url);
post.addHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Accept", "application/json");
post.setEntity(new StringEntity(strJson, Charset.forName("UTF-8")));
try {
response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != response) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}