c# http Post not getting anything in webresponse

2019-07-11 03:23发布

问题:

Here's my code for Request and Response.

System.IO.MemoryStream xmlStream = null;
HttpWebRequest HttpReq = (HttpWebRequest)WebRequest.Create(url); 
xmlStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(format));

byte[] buf2 = xmlStream.ToArray();
System.Text.UTF8Encoding UTF8Enc = new System.Text.UTF8Encoding();
string s = UTF8Enc.GetString(buf2);
string sPost = "XMLData=" + System.Web.HttpUtility.UrlDecode(s);
byte[] bPostData =  UTF8Enc.GetBytes(sPost);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
request.ContentType = "application/x-www-form-urlencoded";
HttpReq.Timeout = 30000;  
request.Method = "POST"; 
request.KeepAlive = true; 
using (Stream requestStream = request.GetRequestStream()) 
{
    requestStream.Write(bPostData, 0, bPostData.Length); 
    requestStream.Close(); 
}

string responseString = "";
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
using (StreamReader sr = new StreamReader(response.GetResponseStream())) 
{ 
    responseString = sr.ReadToEnd(); 
}

No part of this code crashes. The "format" string is the one with XML in it. By the end when you try to see what's in the responseString, it's an empty string. I am supposed to see the XML sent back to me from the URL. Is there something missing in this code?

回答1:

I would recommend a simplification of this messy code:

using (var client = new WebClient())
{
    var values = new NameValueCollection
    {
        { "XMLData", format }
    };
    byte[] resultBuffer = client.UploadValues(url, values);
    string result = Encoding.UTF8.GetString(resultBuffer);
}

and if you wanted to upload the XML directly in the POST body you shouldn't be using application/x-www-form-urlencoded as content type. You probably should specify the correct content type, like this:

using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "text/xml";
    var data = Encoding.UTF8.GetBytes(format);
    byte[] resultBuffer = client.UploadData(url, data);
    string result = Encoding.UTF8.GetString(resultBuffer);
}