2010-06-21 73 views
11

我想將URL編碼的帖子發送到PHP中實現的REST API。 POST數據包含兩個用戶提供的字符串:如何使用HttpWebRequest在POST中轉義URL編碼數據

WebRequest request = HttpWebRequest.Create(new Uri(serverUri, "rest")); 
request.Method = "POST"; 
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; 
request.Headers.Add("Content-Transfer-Encoding", "binary"); 

// Form the url-encoded credentials we'll use to log in 
StringBuilder builder = new StringBuilder(); 
builder.Append("user="); 
builder.Append(user); 
builder.Append("&password="); 
builder.Append(password); 
byte[] credentials = Encoding.UTF8.GetBytes(builder.ToString()); 

// Write the url-encoded post data into the request stream. 
request.ContentLength = credentials.Length; 
using (Stream requestStream = request.GetRequestStream()) { 
    requestStream.Write(credentials, 0, credentials.Length); 
} 

此發送一個HTTP請求以UTF-8作爲其POST數據含有user=myusername&password=mypassword服務器。

如何逃避用戶提供的字符串? 例如,如果我有一個名爲big&mean的用戶,應如何轉義&,以便它不會弄亂請求行?

回答

17

您可以使用System.Web中的靜態HttpUtility類來編碼和解碼HTML和Url相關的值。

嘗試HttpUtility.UrlEncode()

+0

謝謝!如果我在包含UTF-8字符的字符串(如德語s-z)上使用該方法,則UTF-8代碼對變爲「%c3%9f」。我認爲這意味着'Content-Transfer-Encoding'現在應該被設置爲'7bit'? – Cygon 2010-06-22 09:38:53

+0

您可以使用HttpUtility.UrlEncode提供的參數之一是編碼。 '%'後面使用的字符數取決於編碼。 – pauloya 2010-07-29 08:11:20

-3

這似乎是的System.Web過時 - 訪問它的新方法是System.Net.WebUtility.HtmlEncode

+9

HtmlEncode用於轉義HTML中的數據,而不是URL。 – Ralf 2011-11-03 16:19:36

+1

HtmlEncode與UrlEncode不一樣。 HtmlEncode會將「<」轉換爲「<」,而UrlEncode將轉換爲「%3c」。 – 2015-02-16 21:56:16