2014-01-07 84 views
0

我正在編程嘗試POST到Web服務。我面臨的問題是我發佈的數據。
儘管POST數據的編碼

string post_data = "man=HE&game=01&&address=123 Main St.&cap=1,2,3,4"; 
new ASCIIEncoding().GetBytes(post_data) 

它沒有得到轉化爲

man=HE&game=01&&address=123+Main+St.&cap=1%2C2%2C3%2C4 

什麼是解決它的最好方法?

回答

3

你只是以這種方式得到一個字節流。爲了URL編碼字符串中,你可以使用HttpUtility輔助類的URLEncode方法:

string post_data = "man=HE&game=01&&address=123 Main St.&cap=1,2,3,4"; 

string[] postTokens = post_data.Split(new Char [] {'&'}); 
for(int i = 0; i < postTokens.Length; i++) 
{ 
    int pos = postTokens[i].IntexOf("="); 
    string name = postTokens[i].Substring(0, pos); 
    string value = postTokens[i].Substring(pos + 1); 

    postTokens[i] = String.Format("{0}={1}", name, HttpUtility.UrlEncode(value)); 
}  

string encodedPostData = String.Join("=", postTokens); 

var encodedPostDataBytes = ASCIIEncoding.GetBytes(encodedPostData); 
+0

在這個例子中,他們需要編碼單個參數,而不是整個字符串。 – Matthew

+0

@Matthew你是絕對正確的! –

1

我想你混淆ASCII編碼與URL編碼。

您會想要使用System.Web.HttpServerUtility.UrlEncode方法並分別對查詢字符串的每個元素進行編碼。

string post_data = 
    "man=" + HttpUtility.UrlEncode("HE") + 
    "&game=" + HttpUtility.UrlEncode("01") // and so forth