加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用C#远程HTTP发布

发布时间:2020-12-15 19:54:13 所属栏目:百科 来源:网络整理
导读:参见英文答案 How to make HTTP POST web request????????????????????????????????????9个 你如何在C#中进行远程HTTP发布(请求)? 解决方法 这是我写过的一个小应用程序的代码,用于将带有值的表单发布到URL.它应该非常强大. _formValues是一个字典 string,s
参见英文答案 > How to make HTTP POST web request????????????????????????????????????9个
你如何在C#中进行远程HTTP发布(请求)?

解决方法

这是我写过的一个小应用程序的代码,用于将带有值的表单发布到URL.它应该非常强大.

_formValues是一个字典< string,string>包含要发布的变量及其值.

// encode form data
StringBuilder postString = new StringBuilder();
bool first=true;
foreach (KeyValuePair pair in _formValues)
{
    if(first)
        first=false;
    else
        postString.Append("&");
    postString.AppendFormat("{0}={1}",pair.Key,System.Web.HttpUtility.UrlEncode(pair.Value));
}
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] postBytes = ascii.GetBytes(postString.ToString());

// set up request object
HttpWebRequest request;
try
{
    request = WebRequest.Create(url) as HttpWebRequest;
}
catch (UriFormatException)
{
    request = null;
}
if (request == null)
    throw new ApplicationException("Invalid URL: " + url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;

// add post data to request
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes,postBytes.Length);
postStream.Close();

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读