用C#远程HTTP POST [英] Remote HTTP Post with C#

查看:170
本文介绍了用C#远程HTTP POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你怎么做在C#中远程HTTP POST(要求)?

How do you do a Remote HTTP Post (request) in C#?

推荐答案

这是从一个小的应用程序,我写一次发布形式值到URL代码。它应该是相当强劲的。

This is code from a small app I wrote once to post a form with values to a URL. It should be pretty robust.

_formValues​​是一个字典<字符串,字符串>包含张贴变量及其值

_formValues is a Dictionary<string,string> containing the variables to post and their values.


// 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;

这篇关于用C#远程HTTP POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆