最近在写后台,所以有些方法想记录下来,下面是百度的身份证验证的接口调用,百度APIStore的地址http://apistore.baidu.com/apiworks/servicedetail/113.html里面有详细的信息,下面是我写的一个方法,仅供参考。
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class IdentityCheck {
/**
* @param httpUrl
* :请求接口
* @param identity
* :身份证号
* @return 返回结果
*/
public boolean Check(String identity){
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
String httpUrl = “http://apis.baidu.com/apistore/idservice/id?id=“+identity;
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
// 填入apikey到HTTP header
connection.setRequestProperty("apikey", "这里填在百度获取的apikey");
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString(); //查询结果是json返回
/* JSON返回示例 :
{
"errNum": 0,
"retMsg": "success",
"retData": {
"sex": "M", //M-男,F-女,N-未知
"birthday": "1987-04-20", //出生日期
"address": "湖北省孝感市汉川市" //身份证归属地 市/县
}
}*/
JsonParser jP = new JsonParser();
JsonObject jobj=jP.parse(result).getAsJsonObject(); //解析数据
String errNum = jobj.get("errNum").getAsString();
if(errNum.equals("0")){
//身份证合法返回true
return true;
}else {
//不合法返回false
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}