[英]Debugging an HttpWebResponse
這是在Windows Forms應用程序上完成的。 我花了很多時間在調試器中逐步完成此代碼。 我發現了以下內容,它們似乎都在這一行:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
1.如果我包括
request.SendChunked = true;
我在前面所述的響應行中收到此錯誤:
'System.Net.WebException: The remote server returned an error: (415) Unsupported Media Type.
2.如果我注釋掉#1中的代碼,則會在開始提到的主要響應行中收到此錯誤:
'System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly.
3.如果我使用路由#1,則請求的“連接”始終保持為“ KeepAlive”。 但是,如果我使用路由#2,則請求的“連接”在開始時提到的響應行上將變為“空”。
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);
}
}
我覺得這些東西正逐步形成一個解決方案,但我確實可以使用一些指導。
request.ContentType = "application/xml";
如果您的服務器只希望使用“ application / x-www-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
如果您以第一種方法查看響應,請執行以下操作: 415-不支持的媒體類型 ,您可能會注意到您指定的內容類型( “ application / x-www-form-urlencoded” )與您的內容不匹配在正文中發送(一個XML文檔)。 發送文件時應啟用塊編碼。
如果您在用源代碼完成請求時遇到麻煩,請嘗試使用Web調試工具(例如Fiddler)單獨測試該請求。 在那里,您將撰寫並發出請求,直到獲得所需的響應為止。 然后,您可以將其與源代碼發送的內容進行比較(再次,您應使用相同的工具檢查您的請求)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.