我有一个独特的请求,我需要发送JSON POST请求但是读取XML GET。我在下面尝试了这个,但是我收到错误
在调用[Begin] GetResponse之前,必须将ContentLength字节写入请求流。
为了让我的XML GET能够成功读取响应,我会改变什么?
public bool PerformPost(Dictionary<string, string> dictFormValues, string strPageTitle, string strPageURL, ref string strMessage)
{
string strEndpointURL = string.Format("websitegoeshere");
System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
string strPostData = "";
foreach (var d in dictFormValues) { strPostData += d.Key + "=" + Server.UrlEncode(d.Value) + "&"; }
strPostData += "hs_context=";
HttpWebRequest r = (System.Net.HttpWebRequest)WebRequest.Create(strEndpointURL);
r.Method = "POST";
r.Accept = "application/json";
r.ContentType = "application/x-www-form-urlencoded";
r.ContentLength = strPostData.Length;
r.KeepAlive = false;
Stream datastream = r.GetRequestStream();
WebResponse response = r.GetResponse();
datastream = response.GetResponseStream();
StreamReader reader = new StreamReader(datastream);
string responsefromserver = reader.ReadToEnd();
var xml = System.Xml.Linq.XElement.Parse(responsefromserver);
if (xml.Elements("sid").FirstOrDefault().Value == "1") { return true; }
else
{
var errors = xml.Elements("fail");
foreach (var error in errors.Elements("fail"))
{
strMessage = error.Value;
return false;
}
}
reader.Close();
datastream.Close();
response.Close();
return true;
}
答案 0 :(得分:1)
您尚未将发布数据写入请求流。在调用GetResponse之前,您需要调用datastream.Write。
例如:
var buffer = Encoding.UTF8.GetBytes(strPostData);
r.ContentLength = buffer.Length;
datastream.Write(buffer, 0, buffer.Length);
datastream.Close();