利用httpwebrequest解析网站的文本文件

首先是一个这样的文本文件:

username='jim'

useraccount='jim2012'

 

username='jim1'

useraccount='jim12012'

 

然后需要读取它,并显示到一个aspx文件上,我是怎样做的呢,首先建立一个ashx文件,然后如下代码

 

public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain;";
            context.Response.ContentEncoding =Encoding.Default;
            context.Response.Write(this.AnalyzeData());
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public string AnalyzeData()
        {
           HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://test.cn/test.txt") as HttpWebRequest;
           Stream stream= httpWebRequest.GetResponse().GetResponseStream();
           StreamReader readStream = new StreamReader(stream,Encoding.Default);
           StringBuilder sbData = new StringBuilder();
           int i = 0;

           while (!readStream.EndOfStream)
           {
               sbData.Append(readStream.ReadLine());

               if (i % 2 == 0 && i!=0)
               {
                   sbData.Append("/");
               }
               sbData.Append(",");
               i = i + 1;
           }
          
           StringBuilder sbData1=new StringBuilder();
         
           string [] a =sbData.ToString().Split('/');
          
            sbData1.Append("[");
           for (int j = 0; j < a.Length-1; j++)
           {
               object[] b = a[j].Split(',');

               sbData1.Append("{");
               sbData1.AppendFormat("username:'{0}',useraccount:'{1}'", b[0], b[1]);
               sbData1.Append("},");
           }

           sbData1.Append("]");

           return sbData1.ToString();
        }

 首先是利用httpwebrequest获取内容,然后进行解析,需要注意的是那个编码设置,要用默认的编码设置,否则中文会变成乱码。然后我把得到的数据编程了json数组。因为客户端,我将用jquery的ajax进行调用,所以我觉定用 json,来做数据交互。

客户端的代码如下:

 

function ShowTestData(){

      $.getJSON("test.ashx",null,function(data){
          
         
           if(data!=null){
          
              for(i in data){
              
                                                           $("#test").html(data[i].username.split("=")[1]);
                 
                  }
             
              }
          
           }  
          
      }
      );
     

  
}

代码都比较简单,大家看看也应该就明白了,所以不做注释了

 

posted @ 2010-12-15 19:21  chenleinet  阅读(286)  评论(0编辑  收藏  举报