伺服器認可通訊協定違規. Section=ResponseStatusLine"
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace htpclinet
{
class Program
{
private static readonly HttpClient client = new HttpClient();
static void Main(string[] args)
{
gethttp();
Console.Read();
}
public static async void gethttp()
{
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var responseString = await client.GetStringAsync("http://localhost:8085//news.html");
Console.WriteLine(responseString);
}
}
}
以上Code其實是不標準的會造成Exception
發現對有的網站用HttpWebrequest抓取網頁的時候會報錯,捕獲異常提示:"服務器提交了協議衝突Section=ResponseStatusLine ”,改用WebClient也是同樣問題,後來知道,WebClient是對HttpWebrequest進一步進行了封裝。
最後終於找到問題根源:The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF微軟沒有容忍不符合RFC 822中的httpHeader必須以CRLF結束的規定的服務器響應。
通過修改配置文件解決:在app.config(WinForm)或web.config(Web)文件裡修改。
起因: Server回覆的訊息,透過.Net會阻擋, 解決方法如下 將以下Code放入App.config內
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
</system.net>
參考網頁
http://stackoverflow.com/questions/8424144/how-to-set-useunsafeheaderparsing-in-code
以上若有謬誤請盡速通知筆者