新手在线求助!关于json
本人在网上找到一段源代码,可以进行IP查询,随后测试了5000余个IP,有20多个在查询中出现异常,异常均为:
System.ArgumentException: 无效的 JSON 基元
以IP 222.25.187.39为例,在百度中可以查询出IP地址,但是在程序中调用方法,确实出现异常。
由于无法联系到提供源码的作者,本人对网页这块了解甚少,望有大神们能够提供改进的方法!
工作环境: VS2010,.net4.0
源码:
/// <summary>
/// 获取IP地址的详细信息,调用的借口为
/// http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip={ip}
/// </summary>
/// <param name="ipAddress">请求分析得IP地址</param>
/// <param name="sourceEncoding">服务器返回的编码类型</param>
/// <returns>IpUtils.IpDetail</returns>
public static IpDetail Get(String ipAddress, System.Text.Encoding sourceEncoding)
{
String ip = string.Empty;
if (sourceEncoding == null)
sourceEncoding = System.Text.Encoding.UTF8;
using (var receiveStream = System.Net.WebRequest.Create("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=" + ipAddress).GetResponse().GetResponseStream())
{
using (var sr = new System.IO.StreamReader(receiveStream, sourceEncoding))
{
var readbuffer = new char[256];
int n = sr.Read(readbuffer, 0, readbuffer.Length);
int realLen = 0;
while (n > 0)
{
realLen = n;
n = sr.Read(readbuffer, 0, readbuffer.Length);
}
ip = sourceEncoding.GetString(sourceEncoding.GetBytes(readbuffer, 0, realLen));