我会说它不是一个 XML,而只是一个由以下内容细分的字符串;
:
通过给出一个不可能的 IP 地址,我们可以看到它是这样组成的:
OK;;74.125.45.100;US;UNITED STATES
ERROR;Invalid IP address.;127.0.0.1.1;;
OK/ERROR
If ERROR, complete ERROR message
IP Address
Abbreviation of country
Country name
这段代码应该这样做:
string userIP = "127.0.0.1";
string apiKey = "5d3d0cdbc95df34b9db4a7b4fb754e738bce4ac914ca8909ace8d3ece39cee3b";
string url = "http://api.ipinfodb.com/v3/ip-country/?key=" + apiKey + "&ip=" + userIP;
WebRequest request = WebRequest.Create(url);
using (var response = (HttpWebResponse)request.GetResponse())
{
// We try to use the "correct" charset
Encoding encoding = response.CharacterSet != null ? Encoding.GetEncoding(response.CharacterSet) : null;
using (var sr = encoding != null ? new StreamReader(response.GetResponseStream(), encoding) :
new StreamReader(response.GetResponseStream(), true))
{
var response2 = sr.ReadToEnd();
var parts = response2.Split(';');
if (parts.Length != 5)
{
throw new Exception();
}
string okError = parts[0];
string message = parts[1];
string ip = parts[2];
string code = parts[3];
string country = parts[4];
}
}