我正在尝试将简单的文本数据提交到多部分形式的 CGI。
问题是..我不知道如何格式化表单数据!
简而言之,我的系统准备一个包含 post 数据的字符串,使用 request.GetRequestStream() 创建一个 streamwriter,然后将 post string 直接写入该 streamwriter。然后它继续关闭流写入器,并发送请求。
我尝试将字符串格式化为:“Param1=sometext¶m2=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();