开发者

HttpRequest and POST

I keep getting one of the following error messages :

"The remote server returned an error: (400) Bad Request."  
               OR
"System.Net.ProtocolViolationException: You must write ContentLength bytes to the request stream b开发者_如何学编程efore calling [Begin]GetResponse."

Here is the code I'm running :

        StringBuilder bld = new StringBuilder();
        bld.Append("contractId=");
        bld.Append(ctrId);
        bld.Append("&companyIds=");
        bld.Append("'" + company1+ ", " + company2+ "'");

        HttpWebRequest req = (HttpWebRequest)WebRequest
            .Create(secureServiceUrl + "SetContractCompanyLinks");
        req.Credentials = service.Credentials;
        //req.AllowWriteStreamBuffering = true;
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = bld.Length;
        StreamWriter writer = new StreamWriter(req.GetRequestStream());
        var encodedData = Encoding.ASCII.GetBytes(bld.ToString());
        writer.Write(encodedData);
        writer.Flush();
        writer.Close();
        var resp = req.GetResponse();


A couple things that are "off":

Write directly to your writer There shouldn't be a reason to call GetBytes(). The StreamWriter is perfectly capable of writing a string to the stream:

writer.Write(bld.ToString());

Use the using() {} pattern around your StreamWriter

This will ensure proper disposal of the writer object.

using(var writer = new StreamWriter(req.GetRequestStream()))
{
   writer.Write(bld.ToString());
}

You don't need to explicitly set the content length Leave it alone, the framework will set it for you based on what you write to the request stream.

If you need to be explicit about using ASCII, set the charset in the Content-Type header

req.ContentType = "application/x-www-form-urlencoded; charset=ASCII";

You should also specify the encoding when instantiating your StreamWriter:

new StreamWriter(req.GetRequestStream(), Encoding.ASCII)


    req.ContentLength = bld.Length;
    StreamWriter writer = new StreamWriter(req.GetRequestStream());
    var encodedData = Encoding.ASCII.GetBytes(bld.ToString());
    writer.Write(encodedData);

You are not writing what you say you are going to be writing- you write the ASCII encoded bytes not your original byte array - the ContentLength has to match the number of bytes you write. Instead do:

    var encodedData = Encoding.ASCII.GetBytes(bld.ToString());
    req.ContentLength = encodedData.Length;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜