我正在尝试在.NET Compact Framework上执行HTTP POST REQUEST,但我无法使其正常工作。
这就是我得到的:
public static string DoPost(string url)
{
// initialize from variables
string responseString = string.Empty;
ASCIIEncoding encoding = new ASCIIEncoding();
//// UTF8Encoding encoding = new UTF8Encoding();
HttpWebResponse response;
byte[] data = encoding.GetBytes("dummy");
StreamReader reader;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
//do the processing
SetRequestProperties(request, "POST"); // SETTING METHOD TO POST HERE
request.GetRequestStream().Write(data, 0, data.Length);
request.GetRequestStream().Close();
response = (HttpWebResponse)request.GetResponse();
reader = new StreamReader(response.GetResponseStream());
responseString = reader.ReadToEnd();
//clean up
response.Close();
response.GetResponseStream().Close();
reader.Close();
reader = null;
response = null;
request = null;
encoding = null;
//return
MessageBox.Show("POST SUCCESS");
return responseString;
}
private static void SetRequestProperties(HttpWebRequest request, string s)
{
request.Method = s;
request.AllowWriteStreamBuffering = true;
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
request.SendChunked = false;
request.Credentials = CredentialCache.DefaultCredentials;
request.UserAgent = "my mobile user agent";
request.Timeout = 60000;
request.ProtocolVersion = new System.Version("1.1");
}
...但由于某些原因,它总是发送0长度的二进制数据。代码似乎与WinForms和Webpages一起使用,但不适用于CF.
我的代码中有什么错误或遗忘的内容?
由于
答案 0 :(得分:1)
我没有看到你设置request.ContentLength。这是我使用的代码,我知道它可以工作:
private string SendData(string method, string directory, string data)
{
string page = string.Format("http://{0}/{1}", DeviceAddress, directory);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(page);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = method;
CredentialCache creds = GenerateCredentials();
if (creds != null)
{
request.Credentials = creds;
}
// turn our request string into a byte stream
byte[] postBytes;
if(data != null)
{
postBytes = Encoding.UTF8.GetBytes(data);
}
else
{
postBytes = new byte[0];
}
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
return GetResponseData(response);
}
public string Post(string directory, string data)
{
return SendData("POST", directory, data);
}