HttpWebRequest:post数据到博客园
public HttpResponseMessage GetNextNews(int pageIndex=2) { NewsManage news = new NewsManage(); return toJson(news.GetNextNews("http://www.cnblogs.com/mvc/AggSite/PostList.aspx", pageIndex)); }
public List<T_News> GetNextNews(string url,int pageIndex=2) { string result = ""; HttpWebRequest request = null; try { //paraData表示提交参数,以&符分隔 string paraData =string.Format("CategoryType=SiteHome&ParentCategoryId=0&CategoryId=808&PageIndex={0}&TotalPostCount=4000&ItemListActionName=PostList",pageIndex); request = (HttpWebRequest)WebRequest.Create(url); request.Method = "post";//以post方式提交 /* 1、form的enctype属性为编码方式,常用的2种:application/x-www-form-urlencoded和multipart/form-data 2、默认为application/x-www-form-urlencoded,(1)、action为get方式时,游览器用application/x-www-form-urlencoded的编码方式 * 把form数据换成字符串(key1=value1&key2=value2&key3=value3...),然后把字符串append到url后面,用?分隔; * (2)、如果action为post方式,游览器把form数据封装到http body中,然后发送到server 3、如果存在type=file的控件元素,就要用到multipart/form-data,浏览器会把整个表单以控件为单位分割, * 并为每个部分加上Content-Disposition(form-data或者file),Content-Type(默认为text/plain),name(控件name)等信息,并加上分割符(boundary) */ request.ContentType = "application/x-www-form-urlencoded"; //request.ContentType = "appliction/json"; using (Stream stream = request.GetRequestStream()) { //提交数据 byte[] bytes = Encoding.UTF8.GetBytes(paraData); stream.Write(bytes,0,bytes.Length); } //获取响应 using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)//返回Internet资源响应 { using (Stream responseStream = response.GetResponseStream())//获取响应流 { using (StreamReader reader = new StreamReader(responseStream,Encoding.UTF8))//以特定格式读取数据流 { result = reader.ReadToEnd(); } } } } catch { } return GetNextNews(result); }
public List<T_News> GetNextNews(string htmlContent) { List<T_News> newsList = new List<T_News>(); /* 1、\s*表示多个空格 2、(?<href>[^""]*)把不是""的所有其他字符匹配,然后放在href组里 3、(?<title>[^>]*)把不是>的所有其他字符放在title组里 */ string strPattern = "<a\\s*class=\"titlelnk\"\\s*href=\"http://www.cnblogs.com/(?<href>[^\"\"]*)\"\\s*target=\"_blank\">(?<title>[^>]*)</a>"; Regex regex = new Regex(strPattern, RegexOptions.IgnoreCase); if (regex.IsMatch(htmlContent)) { MatchCollection matchCollection = regex.Matches(htmlContent); foreach (Match match in matchCollection) { newsList.Add(new T_News {Title=match.Groups["title"].ToString(),Content=match.Groups["href"].ToString()}); } } return newsList; }
前端调用
var url = "http://10.100.22.54:8095/api/NewsManager/GetNextNews";//请求地址部署在IIS上的webapi var dataParam = { pageIndex: pageIndex }; $.get(url, dataParam, function (data) { $ul.empty(); $.each(data, function (key, value) { var title = value.Title; $ul.append('<li class="list-li"><div class="con" data-href=' + value.Content + '>' + (title.gblen() > 40 ? title.gbsub(37) : title) + '<div class="btn" data-id=' + value.ID + '>删除</div>' + '</li></div>'); }) }, "json").done(function () {//数据加载成功后执行,done为回调函数 $(".list").height($(window).height() - $("header").height() - 10); });

浙公网安备 33010602011771号