我想將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
的用戶,應如何轉義&,以便它不會弄亂請求行?
謝謝!如果我在包含UTF-8字符的字符串(如德語s-z)上使用該方法,則UTF-8代碼對變爲「%c3%9f」。我認爲這意味着'Content-Transfer-Encoding'現在應該被設置爲'7bit'? – Cygon 2010-06-22 09:38:53
您可以使用HttpUtility.UrlEncode提供的參數之一是編碼。 '%'後面使用的字符數取決於編碼。 – pauloya 2010-07-29 08:11:20