WebRequest with POST-parameters in .NET Compact Framework

血红的双手。 提交于 2019-12-04 19:55:15

I don't see you setting the request.ContentLength. Here's code that I use that I know works:

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!