c# http Post not getting anything in webresponse

℡╲_俬逩灬. 提交于 2020-01-05 03:05:24

问题


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);
}


来源:https://stackoverflow.com/questions/6077862/c-sharp-http-post-not-getting-anything-in-webresponse

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