c# - 使用 HttpWebRequest 发布表单数据

标签 c# post httpwebrequest

我想将一些表单数据发布到不在我自己的 Web 应用程序内的指定 URL。它具有相同的域,例如“domain.client.nl”。 Web应用程序有一个url“web.domain.client.nl”,我想发布到的url是“idp.domain.client.nl”。 但我的代码什么也没做......有人知道我做错了什么吗?

沃特

StringBuilder postData = new StringBuilder();
postData.Append(HttpUtility.UrlEncode(String.Format("username={0}&", uname)));
postData.Append(HttpUtility.UrlEncode(String.Format("password={0}&", pword)));
postData.Append(HttpUtility.UrlEncode(String.Format("url_success={0}&", urlSuccess)));
postData.Append(HttpUtility.UrlEncode(String.Format("url_failed={0}", urlFailed)));

ASCIIEncoding ascii = new ASCIIEncoding();
byte[] postBytes = ascii.GetBytes(postData.ToString());

// set up request object
HttpWebRequest request;
try
{
    request = (HttpWebRequest)HttpWebRequest.Create(WebSiteConstants.UrlIdp);
}
catch (UriFormatException)
{
    request = null;
}
if (request == null)
    throw new ApplicationException("Invalid URL: " + WebSiteConstants.UrlIdp);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

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

最佳答案

字段名称和值都应该进行 url 编码。 发布数据和查询字符串的格式相同

.net 的做法是这样的

NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
outgoingQueryString.Add("field1","value1");
outgoingQueryString.Add("field2", "value2");
string postdata = outgoingQueryString.ToString();

这将负责对字段和值名称进行编码

关于c# - 使用 HttpWebRequest 发布表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59280554/

相关文章:

rest - 制作 Postman 测试 - Grails

jquery - Rails 无法正确解码来自 jQuery 的 JSON(数组变成带有整数键的散列)

java - Spring中客户端向服务器端发送数据

c# - 如何使用 C# 访问 ListBox 中的 TextBlock

c# - 如何使用 signalr 以 Angular 读取从 web api 发送的数据?

c# - ArgumentException: 给定的端口名称不以 COM/com 开头或未解析为有效的串行端口

c# - SetUserAlarm Okuma THINC API C#

security - 欺骗 Paypal 托管页面静默发布

c# - 可移植类库和 WebRequest.ContentLength

ASP.NET 在请求期间存储上下文数据