http协议:
国内大陆优化(支持ipv6)http://api.ipshudi.com/ipdata/
国际各洲覆盖(部份ipv6)http://api.ip138.com/ipdata/
https协议:
国内大陆优化(支持ipv6)https://api.ipshudi.com/ipdata/
国际各洲覆盖(部份ipv6)https://api.ip138.com/ipdata/
* API接口可能会因为各种网络原因和攻击都可能产生阻断,请开发时做好冗余和异常处理
* 当HTTP请求返回的状态码非200时,请做异常处理,比如 202 状态码造成的原因可能是无效Token、余额不足、格式错误
Go语言调用iP查询接口示例:
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
)
const (
URL = "https://api.ip138.com/ipdata/"
TOKEN = "bd4c2bf9a38ab06f7cae88c9759ee172"
)
//----------------------------------
// iP地址调用示例代码
//----------------------------------
// xml struct
type xmlinfo struct {
Ret string `xml:"ret"`
Ip string `xml:"ip"`
Data locationxmlInfo `xml:"data"`
}
type locationxmlInfo struct {
Country string `xml:"country"`
Region string `xml:"region"`
City string `xml:"city"`
District string `xml:"district"`
Isp string `xml:"isp"`
Zip string `xml:"zip"`
Zone string `xml:"zone"`
Tag string `xml:"tag"`
}
//json struct
type jsoninfo struct {
Ret string `json:"ret"`
Ip string `json:"ip"`
Data [8]string `json:"data"`
}
func main() {
ipLocation("8.8.8.8","xml")
}
func ipLocation(ip string,dataType string) {
queryUrl := fmt.Sprintf("%s?ip=%s&datatype=%s",URL,ip,dataType)
client := &http.Client{}
reqest, err := http.NewRequest("GET",queryUrl,nil)
if err != nil {
fmt.Println("Fatal error ",err.Error())
}
reqest.Header.Add("token",TOKEN)
response, err := client.Do(reqest)
defer response.Body.Close()
if err != nil {
fmt.Println("Fatal error ",err.Error())
}
if response.StatusCode == 200 {
bodyByte, _ := ioutil.ReadAll(response.Body)
if dataType == "jsonp" {
var info jsoninfo
json.Unmarshal(bodyByte,&info)
fmt.Println(info.Ip)
} else if dataType == "xml" {
var info xmlinfo
xml.Unmarshal(bodyByte,&info)
fmt.Println(info.Ip)
}
}
return
}