2
這是我的代碼Request and Response。c#http在web響應中沒有得到任何東西
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();
}
此代碼沒有任何部分崩潰。 「格式」字符串是其中包含XML的字符串。最後,當您嘗試查看responseString
中的內容時,它是一個空字符串。我應該看到從URL發回給我的XML。這段代碼中是否有缺失?
我無法在namevaluecollection中發送。我需要發送XML – lkwewpp 2011-05-20 22:06:23
@lkwewpp,它是我的示例中發送的XML。你試過了嗎?如果'format'變量包含XML,則WebClient將使用'application/x-www-form-urlencoded' POST請求並在XMLData字段中發送XML,並負責正確編碼它。如果你想在POST主體中發送XML,那麼你根本不應該使用'application/x-www-form-urlencoded'。 – 2011-05-20 22:10:19