http協議:
http://api.youripapi.com/ip/
https協議:
https://api.youripapi.com/ip/
* API接口可能會因為各種網絡原因和攻擊都可能産生阻斷,請開發時做好冗餘和異常處理
* 當HTTP請求返回的狀態碼非200時,請做異常處理,比如 202 狀態碼造成的原因可能是無效Token、餘額不足、格式錯誤
Go語言調用iP查詢接口示例:
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
)
const (
URL = "https://api.youripapi.com/ip/"
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"`
Isp string `xml:"isp"`
Zip string `xml:"zip"`
Zone string `xml:zone`
}
//json struct
type jsoninfo struct {
Ret string `json:"ret"`
Ip string `json:"ip"`
Data [6]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
}