利用Gson获取淘宝IP地址

淘宝IP地址查询提供了API可以调用,返回的是JSON格式的数据流

1. 请求接口(GET):

http://ip.taobao.com/service/getIpInfo.php?ip=[ip地址字串]

2. 响应信息:

(json格式的)国家 、省(自治区或直辖市)、市(县)、运营商

3. 返回数据格式:

{"code":0,"data":{"ip":"210.75.225.254","country":"\u4e2d\u56fd","area":"\u534e\u5317",
"region":"\u5317\u4eac\u5e02","city":"\u5317\u4eac\u5e02","county":"","isp":"\u7535\u4fe1",
"country_id":"86","area_id":"100000","region_id":"110000","city_id":"110000",
"county_id":"-1","isp_id":"100017"}}
其中code的值的含义为,0:成功,1:失败。


Gson是google提供的用来解析json数据格式的库。解析淘宝返回的IP要用到JsonReader包

/**
	 * 通过IP获取地址
	 * 
	 * @param ip
	 * @return
	 */
	public static String getIpInfo(String ip) {
		String info = "";
		try {
			URL url = new URL("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip);
			HttpURLConnection htpcon = (HttpURLConnection) url.openConnection();
			htpcon.setRequestMethod("GET");
			htpcon.setDoOutput(true);
			htpcon.setDoInput(true);
			htpcon.setUseCaches(false);

			InputStream in = htpcon.getInputStream();
			JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
			reader.beginObject();
		    while (reader.hasNext()) {
		        String name = reader.nextName();
		        if (name.equals("code")) {
		          if(reader.nextInt()==1)
		          {
		        	  return info;
		          }
		        } 
		        else if (name.equals("data")) {
		          return readData(reader);
		        } else {
		          reader.skipValue();
		        }
		      }
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return info;
	}
	
	//读取IP数据
    public static String readData(JsonReader reader) throws IOException {
	     String info = "";

	     reader.beginObject();
	     while (reader.hasNext()) {
	       String name = reader.nextName();
	       if (name.equals("country")) {
	    	   info += reader.nextString()+" ";
	       } else if (name.equals("region")) {
	    	   info += reader.nextString()+" ";
	       } else if (name.equals("city")) {
	    	   info += reader.nextString()+" ";
	       } else if (name.equals("isp")) {
	    	   info += reader.nextString()+" ";
	       }  
	       else {
	         reader.skipValue();
	       }
	     }
	     reader.endObject();
	     return info;
	}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值