所需工具:1、elipse 2、json所需jar包
代码:
package com.mobilephone;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import net.sf.json.JSONObject;
public class MainActivity {
/**
* @param urlAll
* :请求接口
* @param httpArg
* :参数
* @return 返回结果
*/
public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
httpUrl = httpUrl + "?" + httpArg;
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// 填入apikey到HTTP header
connection.setRequestProperty("apikey", "73d6548dfb7223d3421608255a592ac3");
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();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
String resout = "";
String httpUrl = "http://apis.baidu.com/apistore/mobilenumber/mobilenumber";
String phonenum = "110";
String httpArg = "phone=" + phonenum;
String jsonResult = request(httpUrl, httpArg);
System.out.println(jsonResult);
JSONObject obj = JSONObject.fromObject(jsonResult);
String code = obj.get("errNum").toString();
if (code.equals("0")) {
JSONObject obj2 = (JSONObject) obj.get("retData");
resout = obj2.get("province") + "-" + obj2.get("city") + "-" + obj2.get("supplier") + "-"
+ obj2.get("suit");
} else {
resout = obj.get("retMsg").toString();
}
System.out.println(resout);
}
}