2010-08-20 25 views
2

好吧,所以問題是我想通過HTTP編碼爲base64發送一個字節數組。雖然我在另一端收到的字符串與原始字符串的大小相同,但字符串本身並不相同,因此我無法將字符串解碼回原始字節數組。問題通過HTTP發送一個base64編碼的字符串與.NET

此外,我發送字符串之前,已完成從客戶端base64轉換/從一切正常工作。發送後發生問題。

有什麼我失蹤?任何特定的格式類型?我試過使用EscapeData(),但字符串太大。

預先感謝您

編輯:代碼

System.Net.WebRequest rq = System.Net.WebRequest.Create("http://localhost:53399/TestSite/Default.aspx"); 
rq.Method = "POST"; 
rq.ContentType = "application/x-www-form-urlencoded"; 
string request = string.Empty; 
string image =    Convert.ToBase64String(System.IO.File.ReadAllBytes("c:\\temp.png"));    
request += "image=" + image; 
int length = image.Length; 
byte[] array = new UTF8Encoding().GetBytes(request); 
rq.ContentLength = request.Length; 
System.IO.Stream str = rq.GetRequestStream();       
str.Write(array, 0, array.Length);    
System.Net.WebResponse rs = rq.GetResponse(); 
System.IO.StreamReader reader = new System.IO.StreamReader(rs.GetResponseStream()); 
string response = reader.ReadToEnd(); 
reader.Close(); 
str.Close();    
System.IO.File.WriteAllText("c:\\temp\\response.txt", response); 
+1

請提供示例代碼,或至少指定*您要發送值的位置,例如正文或網址。 – 2010-08-20 10:02:18

+0

另外,您知道,如果通過GET參數發送,則存在大小限制? – 2010-08-20 10:05:14

+0

我正在發佈它。我將添加一些代碼片段。 – mtranda 2010-08-20 10:32:16

回答

0

我會建議兩件事情來嘗試

  1. 包括字符集的內容類型,你是依靠UTF8 -

    rq.ContentType =「application/x-www-form-urlencoded; charset = utf-8」

  2. 使用StreamWriter在您使用StreamReader進行讀取時寫入請求流。

5

下面的第二行是問題所在。

 
string image = Convert.ToBase64String(System.IO.File.ReadAllBytes("c:\temp.png")); 
request += "image=" + image; 

如果你看一下Base 64 index table,最後兩個字符(+和/)未進行網址安全。所以,當你追加請求時,你必須對URL進行編碼。

我不是一個.NET的傢伙,但第二行應該寫成類似

 
string image = Convert.ToBase64String(System.IO.File.ReadAllBytes("c:\temp.png")); 
request += "image=" + URLEncode(image); 

需要在服務器端沒有變更。只需找出系統調用URL的內容就可以對一段字符串進行編碼。

+0

是的,之前被這個刺痛過! – 2010-08-20 15:58:27

相關問題