我正在尝试将简单文本数据提交到多部分格式的CGI。
问题是..我不知道如何格式化表单数据!
简而言之,我的系统准备一个包含post数据的字符串,使用request.GetRequestStream()创建一个streamwriter,并直接将post字符串写入该streamwriter。然后它继续关闭编写器,并发送请求。
我已尝试将字符串格式化为:“Param1 = sometext& param2 = sometext”,但我收到错误:
Unhandled Exception: System.Net.WebException: The remote server returned an error: (417) Expectation Failed.
at System.Net.HttpWebRequest.CheckFinalStatus (System.Net.WebAsyncResult result) [0x002d9] in /private/tmp/monobuild/build/BUILD/mono-2.8/mcs/class/System/System.Net/HttpWebRequest.cs:1425
at System.Net.HttpWebRequest.SetResponseData (System.Net.WebConnectionData data) [0x00143] in /private/tmp/monobuild/build/BUILD/mono-2.8/mcs/class/System/System.Net/HttpWebRequest.cs:1250
显然我正在格式化字符串错误,但我不能为我的生活弄清楚如何正确地做到这一点。
有人可以开导我吗? :)
编辑,我也尝试将request.ContentType = "application/x-www-form-urlencoded";
更改为request.ContentType = "multipart/form-data";
。这没有用,但我会这样离开。
编辑:完整代码:
public static string sendReq (string url, string pdata)//Pdata is the string containing form data
{
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
CookieCollection jar = new CookieCollection();
jar.Add(new Cookie("Cookie","Data","Removed","For privacy."));
jar.Add(new Cookie("Cookie","Data","Removed","For privacy."));
jar.Add(new Cookie("Cookie","Data","Removed","For privacy."));
jar.Add(new Cookie("Cookie","Data","Removed","For privacy."));
jar.Add(new Cookie("Cookie","Data","Removed","For privacy."));
l("Loading cookie jar onto request");
CookieContainer cont = new CookieContainer();
cont.Add(jar);
request.CookieContainer = cont;
if (pdata != "")
{
request.Method = "POST";
request.ContentType = "multipart/form-data;";
request.ContentLength = pdata.Length;
StreamWriter stOut = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(pdata);
stOut.Close();
}
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
l("Data was read. ["+count+" bytes]. Encoding to ASCII");
tempString = Encoding.ASCII.GetString(buf, 0, count);
l("Appending to full string");
sb.Append(tempString);
}
}
while (count > 0);
return sb.ToString();
}
处理发送帖子数据的代码部分:
if (pdata != "")
{
request.Method = "POST";
request.ContentType = "multipart/form-data;";
request.ContentLength = pdata.Length;
StreamWriter stOut = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(pdata);
stOut.Close();
}
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
答案 0 :(得分:2)
尝试:
System.Net.ServicePointManager.Expect100Continue = false;
显然, HttpWebRequest 默认添加 Expect 标头,这会混淆很多服务器。
<强>更新强>:
恢复为:
request.ContentType = "application/x-www-form-urlencoded";
因为内容类型和正文中数据的当前组合不匹配。