使用 HttpWebRequest 发布表单数据 [英] Post form data using HttpWebRequest

查看:36
本文介绍了使用 HttpWebRequest 发布表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to post some form data to a specified URL that isn't inside my own web application. It has the same domain, such like "domain.client.nl". The web application has a url "web.domain.client.nl" en the url where I want to post to is "idp.domain.client.nl". But my code does nothing..... does someone knows what I'm doing wrong?

沃特

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 编码的.帖子数据和查询字符串的格式相同

Both the field name and the value should be url encoded. format of the post data and query string are the same

.net 的做法是这样的

The .net way of doing is something like this

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

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

This will take care of encoding the fields and the value names

这篇关于使用 HttpWebRequest 发布表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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