2009-05-25 56 views
11

我試圖執行POST使用WebRequest在C#中的網站。我要發佈的網站是一個SMS網站,而messagetext是網址的一部分。爲了避免URL中的空格,我調用HttpUtility.Encode()來對其進行URL編碼。「無法確定URI的格式」與WebRequest

但我不斷收到URIFormatException - 「無效的URI:URI的格式無法確定」 - 當我使用類似的代碼:當我打電話

string url = "http://www.stackoverflow.com?question=a sentence with spaces"; 
string encoded = HttpUtility.UrlEncode(url); 

WebRequest r = WebRequest.Create(encoded); 
r.Method = "POST"; 
r.ContentLength = encoded.Length; 
WebResponse response = r.GetResponse(); 

發生異常WebRequest.Create ()。

我在做什麼錯?

回答

16

只應編碼參數,而不是整個URL,這樣試試:

string url = "http://www.stackoverflow.com?question=" + HttpUtility.UrlEncode("a sentence with spaces"); 

WebRequest r = WebRequest.Create(url); 
r.Method = "POST"; 
r.ContentLength = encoded.Length; 
WebResponse response = r.GetResponse(); 

編碼整個URL將意味着://和?也得到編碼。編碼後的字符串不再是有效的url。

+0

正如[本SO帖子](http://stackoverflow.com/a/1148326/5838198)中所述,最好使用`Uri.EscapeDataString()`而不是`HttpUtility`或`Server`方法。 – Siavas 2016-12-28 18:41:19

1

UrlEncode只能用於查詢字符串。試試這個:

string query = "a sentence with spaces"; 
string encoded = "http://www.stackoverflow.com/?question=" + HttpUtility.UrlEncode(query); 

代碼的當前版本的URL編碼的URL,這是混淆的WebRequest斜線和結腸。