这是在Windows窗体应用程序上完成的。我花了大量的时间在调试器中完成这段代码。我发现了以下几点,它们似乎都在这条线上:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())request.SendChunked = true;在前面声明的响应行中,我得到了这个错误:
'System.Net.WebException: The remote server returned an error: (415) Unsupported Media Type.'System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly. private void HttpPost()
{
HttpWebRequest request = null;
Uri uri = new Uri("https://post.craigslist.org/bulk-rss/post");
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
XmlDocument doc = new XmlDocument();
doc.Load("XMLFile1.xml");
//request.ContentLength = doc.InnerXml.Length;
request.SendChunked = true;
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(doc.InnerXml);
//request.ContentLength = bytes.Length;
writeStream.Write(bytes, 0, bytes.Length);
}
string result = string.Empty;
request.ProtocolVersion = System.Net.HttpVersion.Version11;
request.KeepAlive = false;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (System.IO.StreamReader readStream = new System.IO.StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
}
catch (Exception e)
{
string innerException = String.Format("Inner exception: '{0}'", e.Data);
string exceptionCause = String.Format("An error occurred: '{0}'", e);
System.IO.File.WriteAllText(@"C:\Users\Nathan\Documents\DebugOutputFile\exception.txt", exceptionCause);
System.IO.File.WriteAllText(@"C:\Users\Nathan\Documents\DebugOutputFile\innerException.txt", innerException);
}
}我觉得这些东西正朝着解决方案的方向发展,但我确实需要一些指导。
发布于 2015-09-12 14:46:19
选项1:更改内容类型以匹配主体编码
request.ContentType = "application/xml";选项2:更改主体编码以匹配指定的内容类型
如果您的服务器只期望“application/x form-urlencoded”,那么您需要更改您的身体编码以适应它,例如:
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
string response = String.Concat("arg=", HttpUtility.UrlEncode(doc.InnerXml))
byte[] bytes = encoding.GetBytes(doc.InnerXml);
//request.ContentLength = bytes.Length;
writeStream.Write(bytes, 0, bytes.Length);
}您需要知道参数名称(上面设置为"arg"),并添加对System.Web的引用(如果没有)。
参见以下XML..。
<?xml version="1.0" encoding="UTF-8"?><test></test>以及用于引用的编码字符串(您的请求主体应该类似于此):
arg=%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%3E%3Ctest%3E%3C%2Ftest%3E解释
如果使用第一种方法获得的响应:XML415-不支持的媒体类型( ("application/x-www-form-urlencoded") ),您可以注意到您指定的内容类型与您在正文中发送的内容(一个XML )不匹配。在发送文件时应启用块编码。
备注
当您在用源代码完成请求时遇到问题时,请尝试使用web调试工具(如http://www.telerik.com/fiddler )单独测试该请求。在那里,您将撰写并发出请求,直到得到所需的响应为止。然后,您可以将其与从源代码发送的内容进行比较(同样,您应该使用相同的工具来检查您的请求)。
https://stackoverflow.com/questions/32539706
复制相似问题