当前位置:  开发笔记 > 编程语言 > 正文

使用C#远程HTTP发布

如何解决《使用C#远程HTTP发布》经验,为你挑选了1个好方法。

你如何在C#中进行远程HTTP发布(请求)?



1> David..:

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

_formValues是一个Dictionary ,包含要发布的变量及其值.

// 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, 0, postBytes.Length);
postStream.Close();

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

推荐阅读
mobiledu2402851377
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有