Java实现手机号码归属地查询
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
?package com.rocky.test;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import .URL;
import .URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.NodeList;
public class Moblie {
/**
*
* 获得soap请求
*
* @param mobileCode
*
* @return
*/
private static String getSoapRequest(String mobileCode) {
StringBuilder sb = new StringBuilder();
sb.append(""
+ "\n"
+ "
+ "xmlns:xsd=\"/2001/XMLSchema\""
+ " "
+ "xmlns:soap=\"/soap/envelope/\">"
+ "\n"
+ "
+ "
+ "
+ "
+ "
+ "
+ "
);
return sb.toString();
}
/**
*
* 发送soap请求到服务器,并接受返回数据
*
* @param mobileCode
*
* @return
*/
private static InputStream getSoapInputStream(String mobileCode) {
try {
String soap = getSoapRequest(mobileCode);
if (soap == null)
return null;
URL url = new URL(
"/WebServices/MobileCodeWS.asmx");
URLConnection conn = url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(soap
.length()));
conn.setRequestProperty("SOAPAction",
"/getMobileCodeInfo");
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(soap);
osw.flush();
osw.close();
InputStream is = conn.getInputStream();
return is;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String getMobileNoTrack(String mobileCode) {
try {
org.w3c.dom.Document document = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
InputStream is = getSoapInputStream(mobileCode);
DocumentBuilder db = dbf.newDocumentBuilder();
document = db.parse(is);
NodeList nl = document
.getElementsByTagName("getMobileCodeInfoResult");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < nl.getLength(); i++) {
org.w3c.dom.Node n = nl.item(i);
if (n.getFirstChild().getNodeValue().equals("手机号码错误")) {
sb = new StringBuffer("#");
System.out.println("手机号码输入有误");
break;
}
sb.append(n.getFirstChild().getNodeValue() + "\n");
}
is.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
// System.out.println(Moblie.getSoapRequest("132********"));
//System.out.println(Moblie.getSoapInputStream("132********"));
System.out.println(Moblie.getMobileNoTrack("132********"));
}
}