惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
博客园 - 【当耐特】
IT之家
IT之家
M
MIT News - Artificial intelligence
酷 壳 – CoolShell
酷 壳 – CoolShell
Martin Fowler
Martin Fowler
V
Visual Studio Blog
F
Fortinet All Blogs
The Cloudflare Blog
Last Week in AI
Last Week in AI
博客园 - 司徒正美
G
Google Developers Blog
Vercel News
Vercel News
爱范儿
爱范儿
小众软件
小众软件
WordPress大学
WordPress大学
I
InfoQ
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
MongoDB | Blog
MongoDB | Blog
A
About on SuperTechFans
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
C
Check Point Blog
Apple Machine Learning Research
Apple Machine Learning Research
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

博客园 - 李昀璟

Export to Excel, Word with css (Cascading Style Sheets) Unit Tests for ASP.NET MVC application that uses resources in code behind. IIS 不能运行asp.net Useful Expressions - Business Correspondence How to Plan a Meeting Useful Expressions for Business Interaction Useful Expressions for Business Language 使用IP或机器名而不是localhost访问DotNetNuke DotNetNuke升级中遇到的问题 DNN端口的问题 升级DotNetNuke DotNetNuke的升级路径 设置为自动启动的WindowService没有开机启动 检测是否连网 C# WinForm 边框阴影窗体 Asp.Net部署问题 MSDTC的折磨 - 李昀璟 - 博客园 常用缩写 日本語文法勉強
PostSubmitter~在WEB应用程序以外的其他程序里提交Web请求的类
李昀璟 · 2011-12-28 · via 博客园 - 李昀璟

如果在WindowService等其他非Web应用里提交一个httpRequest,用这个类比较方便:

 PostSubmitter post=new PostSubmitter();

post.Url="http://seeker.dice.com/jobsearch/servlet/JobSearch";
post.PostItems.Add("op","100");
post.PostItems.Add("rel_code","1102");
post.PostItems.Add("FREE_TEXT","c# jobs");
post.PostItems.Add("SEARCH","");
post.Type=PostSubmitter.PostTypeEnum.Post;
string result=post.Post();

源码: 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Net;
using System.Collections.Specialized;

namespace YourNameSpace
{
    
    /// <summary>
    
/// Submits post data to a url.
    
/// </summary>
    public class PostSubmitter
    {
        /// <summary>
        
/// determines what type of post to perform.
        
/// </summary>
        public enum PostTypeEnum
        {
            /// <summary>
            
/// Does a get against the source.
            
/// </summary>
            Get,
            /// <summary>
            
/// Does a post against the source.
            
/// </summary>
            Post
        }

        private string m_url = string.Empty;
        private NameValueCollection m_values = new NameValueCollection();
        private PostTypeEnum m_type = PostTypeEnum.Get;
        /// <summary>
        
/// Default constructor.
        
/// </summary>
        public PostSubmitter()
        {
        }

        /// <summary>
        
/// Constructor that accepts a url as a parameter
        
/// </summary>
        
/// <param name="url">The url where the post will be submitted to.</param>
        public PostSubmitter(string url)
            : this()
        {
            m_url = url;
        }

        /// <summary>
        
/// Constructor allowing the setting of the url and items to post.
        
/// </summary>
        
/// <param name="url">the url for the post.</param>
        
/// <param name="values">The values for the post.</param>
        public PostSubmitter(string url, NameValueCollection values)
            : this(url)
        {
            m_values = values;
        }

        /// <summary>
        
/// Gets or sets the url to submit the post to.
        
/// </summary>
        public string Url
        {
            get
            {
                return m_url;
            }
            set
            {
                m_url = value;
            }
        }
        /// <summary>
        
/// Gets or sets the name value collection of items to post.
        
/// </summary>
        public NameValueCollection PostItems
        {
            get
            {
                return m_values;
            }
            set
            {
                m_values = value;
            }
        }
        /// <summary>
        
/// Gets or sets the type of action to perform against the url.
        
/// </summary>
        public PostTypeEnum Type
        {
            get
            {
                return m_type;
            }
            set
            {
                m_type = value;
            }
        }
        /// <summary>
        
/// Posts the supplied data to specified url.
        
/// </summary>
        
/// <returns>a string containing the result of the post.</returns>
        public string Post()
        {
            StringBuilder parameters = new StringBuilder();
            for (int i = 0; i < m_values.Count; i++)
            {
                EncodeAndAddItem(ref parameters, m_values.GetKey(i), m_values[i]);
            }
            string result = PostData(m_url, parameters.ToString());
            return result;
        }
        /// <summary>
        
/// Posts the supplied data to specified url.
        
/// </summary>
        
/// <param name="url">The url to post to.</param>
        
/// <returns>a string containing the result of the post.</returns>
        public string Post(string url)
        {
            m_url = url;
            return this.Post();
        }
        /// <summary>
        
/// Posts the supplied data to specified url.
        
/// </summary>
        
/// <param name="url">The url to post to.</param>
        
/// <param name="values">The values to post.</param>
        
/// <returns>a string containing the result of the post.</returns>
        public string Post(string url, NameValueCollection values)
        {
            m_values = values;
            return this.Post(url);
        }
        /// <summary>
        
/// Posts data to a specified url. Note that this assumes that you have already url encoded the post data.
        
/// </summary>
        
/// <param name="postData">The data to post.</param>
        
/// <param name="url">the url to post to.</param>
        
/// <returns>Returns the result of the post.</returns>
        private string PostData(string url, string postData)
        {
            HttpWebRequest request = null;
            if (m_type == PostTypeEnum.Post)
            {
                Uri uri = new Uri(url);
                request = (HttpWebRequest)WebRequest.Create(uri);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = postData.Length;
                using (Stream writeStream = request.GetRequestStream())
                {
                    UTF8Encoding encoding = new UTF8Encoding();
                    byte[] bytes = encoding.GetBytes(postData);
                    writeStream.Write(bytes, 0, bytes.Length);
                }
            }
            else
            {
                Uri uri = new Uri(url + "?" + postData);
                request = (HttpWebRequest)WebRequest.Create(uri);
                request.Method = "GET";
            }
            string result = string.Empty;
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        result = readStream.ReadToEnd();
                    }
                }
            }
            return result;
        }
        /// <summary>
        
/// Encodes an item and ads it to the string.
        
/// </summary>
        
/// <param name="baseRequest">The previously encoded data.</param>
        
/// <param name="dataItem">The data to encode.</param>
        
/// <returns>A string containing the old data and the previously encoded data.</returns>
        private void EncodeAndAddItem(ref StringBuilder baseRequest, string key, string dataItem)
        {
            if (baseRequest == null)
            {
                baseRequest = new StringBuilder();
            }
            if (baseRequest.Length != 0)
            {
                baseRequest.Append("&");
            }
            baseRequest.Append(key);
            baseRequest.Append("=");
            baseRequest.Append(System.Web.HttpUtility.UrlEncode(dataItem));
        }
    }

} 

如果出现 The type or namespace name 'HttpUtility' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)这个错误,请添加System.Web引用到Reference. 这时你可能会发现找不到这个引用,右键点击项目,选择Properties, 如果 Target Framework是 ".Net Framework 4 Client",就改成 ".Net Framework 4". But beware this will close, reopen and rebuild your project (also if you have a web service references these will need to be refreshed)。