å 贴两个类ï¼ä¸ä¸ªæ¯è§£æjsonç(解æjsonçç½ä¸æå¾å¤dllå¯ä»¥ç´æ¥ç¨ï¼ææé½å·®ä¸å¤ï¼è¿éæ¯æèªå·±åç)ï¼ä¸ä¸ªæ¯æåè¿ç¨ä¿¡æ¯ç
using System;
using System.IO;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
namespace Atai.Common.Tools
{
public class ParseJson
{
public ParseJson()
{
}
#region SearchCloseCharIndex
/// <summary>
/// 寻æ¾é
对çå符
/// </summary>
/// <param name="source">æºå符串</param>
/// <param name="openChar"></param>
/// <param name="closeChar"></param>
/// <returns></returns>
private int SearchCloseCharIndex(string source,char openChar, char closeChar)
{
int rVal = -1;
if (string.IsNullOrEmpty(source))
return rVal;
if (openChar == closeChar && (openChar == '\'' || openChar=='\"'))
source = source.Replace("\\\'", "ââ").Replace("\\\"", "â
â
");
char[] charList = source.ToCharArray();
int openCharCount = 0;
int closeCharCount = 0;
for (int i=0;i< charList.Length;i++)
{
char c = charList[i];
if (openChar != closeChar)
{
#region èµ·å§å符 != ç»æå符çæ
åµ
if (openChar == c)
{
openCharCount++;
}
else if (closeChar == c)
{
closeCharCount++;
}
if (openCharCount > 0 && openCharCount == closeCharCount)
{
rVal = i;
break;
}
#endregion
}
else if (openChar == closeChar && openChar==c)
{
#region èµ·å§å符 == ç»æå符çæ
åµ
openCharCount++;
if (openCharCount == 2)
{
rVal = i;
break;
}
#endregion
}
}
return rVal;
}
#endregion
#region ParseJsonArray
/// <summary>
/// å°Jsonæ°ç»å解æå个Json
/// </summary>
private List<string> ParseJsonArray(string jsonArrayString)
{
List<string> jsonList = new List<string>();
if (string.IsNullOrEmpty(jsonArrayString))
return jsonList;
jsonArrayString = jsonArrayString.Trim();
int startIdx = jsonArrayString.IndexOf("{");
if (startIdx < 0)
return jsonList;
int endIdx = this.SearchCloseCharIndex(jsonArrayString, '{', '}');
if (endIdx < 0 || endIdx <= startIdx)
return jsonList;
string item = jsonArrayString.Substring(startIdx + 1, endIdx - startIdx);
jsonList.Add(item);
if (endIdx + 1 < jsonArrayString.Length)
{
jsonArrayString = jsonArrayString.Substring(endIdx + 1);
List<string> list = this.ParseJsonArray(jsonArrayString);
foreach (string json in list)
jsonList.Add(json);
}
return jsonList;
}
#endregion
#region ParseJsonItem
/// <summary>
/// 解æJsonçå±æ§
/// </summary>
private SortedDictionary<string, string> ParseJsonItem(string jsonString)
{
SortedDictionary<string, string> jsonItems = new SortedDictionary<string, string>();
if (string.IsNullOrEmpty(jsonString))
return jsonItems;
jsonString = jsonString.Trim();
if (jsonString.StartsWith("{"))
{
jsonString = jsonString.Substring(1).Trim();
}
if (jsonString.EndsWith("}"))
{
jsonString = jsonString.Substring(0, jsonString.Length - 1).Trim();
}
char[] charList = jsonString.ToCharArray();
if (charList.Length < 1)
return jsonItems;//空å符串,éåº
int startIdx = 0;
if (charList[0] == '\'' || charList[0] == '\"')
startIdx = 1;//第ä¸ä¸ªå符为åæå·æåå¼å·
int endIdx = jsonString.IndexOf(":");
if (endIdx <= startIdx)
return jsonItems;//没ææ¾å°åå·æåå·çä½ç½®çäºèµ·å§ä½ç½®,éåº
string key = jsonString.Substring(startIdx, endIdx - startIdx).Trim();
if (key.EndsWith("'") || key.EndsWith("\""))
{
key = key.Substring(0, key.Length - 1).Trim();
}
string val = "";
//startIdx = endIdx + 1;
if (endIdx + 1 < jsonString.Length)
{
#region è·åå¼
jsonString = jsonString.Substring(endIdx + 1).Trim();
if (jsonString.Length < 1)
return jsonItems;//å¦ææªåååªå©ä¸ç©ºå串,éåº
charList = jsonString.ToCharArray();
startIdx = 0;
switch (charList[0])
{
case '\''://å¼ä¸ºåæå·æ¬èµ·æ¥
case '\"'://å¼ä¸ºåå¼å·æ¬èµ·æ¥
startIdx = 1;
endIdx = this.SearchCloseCharIndex(jsonString, charList[0], charList[0]);
break;
case '['://å¼ä¸ºæ°ç»çæ
åµ
startIdx = 0;
endIdx = this.SearchCloseCharIndex(jsonString, '[', ']') + 1;
break;
case '{'://å¼ä¸ºJsonçæ
åµ
startIdx = 0;
endIdx = this.SearchCloseCharIndex(jsonString, '{', '}') + 1;
break;
default://å
¶å®æ
åµ(æ°å)
startIdx = 0;
endIdx = jsonString.IndexOf(",");
break;
}
if (endIdx > startIdx && endIdx < jsonString.Length)
{
val = jsonString.Substring(startIdx, endIdx - startIdx).Trim().Replace("\\\"", "\"").Replace("\\\'", "\'");
}
#endregion
}
if (!string.IsNullOrEmpty(key) && !jsonItems.ContainsKey(key))
{
jsonItems.Add(key, val);
}
if (endIdx + 1 < jsonString.Length)
{
jsonString = jsonString.Substring(endIdx + 1).Trim();
if (jsonString.StartsWith(","))
{
jsonString = jsonString.Substring(1).Trim();//å¦ææªåå,æ¯éå·å¼å¤´çï¼æéå·æªæ
}
if (jsonString.Length < 1)
return jsonItems;//å¦ææªåååªå©ä¸ç©ºå串,éåº
SortedDictionary<string, string> items = this.ParseJsonItem(jsonString);
foreach (string itemKey in items.Keys)
{
if (!string.IsNullOrEmpty(itemKey) && !jsonItems.ContainsKey(itemKey))
{
jsonItems.Add(itemKey, items[itemKey]);
}
}
}
return jsonItems;
}
#endregion
#region ParseArray
/// <summary>
/// 解æjsonæ°ç»
/// </summary>
/// <param name="jsonArray"></param>
/// <returns></returns>
public List<SortedDictionary<string, string>> ParseArray(string jsonArray)
{
List<SortedDictionary<string, string>> list = new List<SortedDictionary<string, string>>();
List<string> jsonList = this.ParseJsonArray(jsonArray);
foreach (string json in jsonList)
{
list.Add(this.ParseJsonItem(json));
}
return list;
}
#endregion
#region ParseArray
/// <summary>
/// 解æjsonæ°ç»
/// </summary>
/// <param name="jsonList"></param>
/// <returns></returns>
public List<SortedDictionary<string, string>> ParseArray(List<string> jsonList)
{
List<SortedDictionary<string, string>> list = new List<SortedDictionary<string, string>>();
foreach (string json in jsonList)
{
list.Add(this.ParseJsonItem(json));
}
return list;
}
#endregion
#region Parse
/// <summary>
/// 解æå个Json
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public SortedDictionary<string, string> Parse(string json)
{
return this.ParseJsonItem(json);
}
#endregion
#region GetJsonValue
public string GetJsonValue(SortedDictionary<string, string> list, string key)
{
if (list.ContainsKey(key))
return list[key];
return "";
}
#endregion
}
}
æåè¿ç¨æ°æ®ç
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
using System.IO;
using System.Net;
namespace Atai.Common.Tools
{
public class Robots
{
public Robots()
{
}
#region å±æ§
private bool _isError = false;
/// <summary>
/// æ¯å¦åºé
/// </summary>
public bool IsError
{
get { return _isError; }
//set { _isError = value; }
}
//
private string _errorMsg = "";
/// <summary>
/// é误信æ¯
/// </summary>
public string ErrorMsg
{
get { return _errorMsg; }
//set { _errorMsg = value; }
}
private string _UserAgent = "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 5.2; Atai IPOLI ; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
/// <summary>
/// UserAgent
/// </summary>
public string UserAgent
{
get { return _UserAgent; }
set { _UserAgent = value; }
}
private string _ContentType = "";
/// <summary>
/// ååºçå
容类å
/// </summary>
public string ContentType
{
get { return _ContentType; }
}
private string _PageEncoding = "";
public string PageEncoding
{
get { return _PageEncoding; }
}
private HttpStatusCode _HttpStatusCode;
/// <summary>
/// è¿ç¨æå¡å¨ååºç¶æ
/// </summary>
public HttpStatusCode StatusCode
{
get { return _HttpStatusCode; }
}
#endregion
#region è¯å«ç¼ç
private string GetEncoding(string html)
{
string result = "utf-8";
Regex reg_charset = new Regex(@"charset\b\s*=\s*(?<charset>[^""'\s]*)");
if (reg_charset.IsMatch(html))
{
return reg_charset.Match(html).Groups["charset"].Value;
}
return result;
}
#endregion
#region æåè¿ç¨HTML
public string GetHtml(string url)
{
return this.GetHtml(url, "");
}
public string GetHtml(string url, string charset)
{
string result = "";
string referer = url;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//声æä¸ä¸ªHttpWebRequest请æ±
request.Timeout = 30000;//设置è¿æ¥è¶
æ¶æ¶é´
request.UserAgent = this.UserAgent;
request.AllowAutoRedirect = true;
//
request.Referer = referer;//设置æ 头
//
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//HttpStatusCode status = ;
this._HttpStatusCode = response.StatusCode;
if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < 1024 * 2048)//大äº2Mçæ件ä¸è¯»å
{
Stream streamReceive = response.GetResponseStream();//response.ContentType
//Stream streamReceive = Gzip(response);
//Encoding encoding = Encoding.Default;
StreamReader streamReader = null;
if (charset == null || charset == "")
{
streamReader = new StreamReader(streamReceive, Encoding.ASCII);
if (response.CharacterSet != string.Empty)
charset = response.CharacterSet;
else
charset = this.GetEncoding(streamReader.ReadToEnd());
}
this._PageEncoding = charset;
Encoding encoding = Encoding.GetEncoding(charset);//
streamReader = new StreamReader(streamReceive, encoding);
result = streamReader.ReadToEnd();
streamReader.Close();
streamReader.Dispose();
streamReceive.Close();
streamReceive.Dispose();
}
else
{
this._isError = true; this._errorMsg = response.StatusCode.ToString();
}
this._ContentType = response.ContentType;
response.Close();
}
catch (Exception e) { this._isError = true; this._errorMsg = e.ToString(); }
return result;
}
#endregion
#region æç¹å®æ°æ®Postå°è¿ç¨æå¡å¨å¹¶è·åè¿åç»æ
public string Post(string url, string postdata, string charset)
{
string result = "";
string referer = url;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//声æä¸ä¸ªHttpWebRequest请æ±
request.Timeout = 30000;//设置è¿æ¥è¶
æ¶æ¶é´
request.UserAgent = this.UserAgent;
request.AllowAutoRedirect = true;
//
request.Referer = referer;//设置æ 头
request.Method = "POST";
//request.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
request.ContentType = "application/x-www-form-urlencoded";
Encoding encoding = Encoding.GetEncoding(charset);//
byte[] byteArray = encoding.GetBytes(postdata);
request.ContentLength = byteArray.Length;
Stream stream = request.GetRequestStream();
stream.Write(byteArray, 0, byteArray.Length);
stream.Close();
//request.Headers.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//response.CharacterSet
//HttpStatusCode status = ;
//response.StatusCode
if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < 1024 * 2048)//大äº2Mçæ件ä¸è¯»å
{
Stream streamReceive = response.GetResponseStream();
//Stream streamReceive = Gzip(response);
this._PageEncoding = charset;
StreamReader streamReader = new StreamReader(streamReceive, encoding);
result = streamReader.ReadToEnd();
streamReader.Close();
streamReader.Dispose();
streamReceive.Close();
streamReceive.Dispose();
}
else
{
this._isError = true; this._errorMsg = response.StatusCode.ToString();
}
this._ContentType = response.ContentType;
response.Close();
}
catch (Exception e) { this._isError = true; this._errorMsg = e.ToString(); }
return result;
}
#endregion
#region Ping
public static System.Net.NetworkInformation.IPStatus Ping(string ip)
{
System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions();
options.DontFragment = true;
string data = "atai";
byte[] buffer = Encoding.ASCII.GetBytes(data);
//Wait seconds for a reply.
int timeout = 1000;
System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options);
return reply.Status;
}
#endregion
}
}