2010-09-18 162 views
0

我目前正在通过字节数组发送图像数据。但是,我希望将它作为ASCII字符串发送。我怎样才能发送一个ASCII字符串从客户端到服务器在C#中使用HTTP POST?使用HTTP发送ASCII字符串Post

HttpWebRequest webRequest = null; 
    webRequest = (HttpWebRequest)HttpWebRequest.Create("http://192.168.1.2/"); 
    webRequest.ContentType = "application/x-www-form-urlencoded";            
    webRequest.Method = "POST";  

//Assume here, I got the ascii string from image using ImageToBase64() function. 

byte[] buffer = encoding.GetBytes(myString)); //assume myString is an ASCII string 

    // Set content length of our data 
    webRequest.ContentLength = buffer.Length; 

    webStream = webRequest.GetRequestStream(); 
    webStream.Write(buffer, 0, buffer.Length); //This is the only way I know how to send data -using byte array "buffer". But i wan to send data over as ASCII string "myString". How? 
    webStream.Close(); 

    //I used this function to turn an image into ASCII string to be sent 
    public string ImageToBase64(Image image, 
     System.Drawing.Imaging.ImageFormat format) 
    { 
     using (MemoryStream ms = new MemoryStream()) 
     { 
     // Convert Image to byte[] 
     image.Save(ms, format); 
     byte[] imageBytes = ms.ToArray(); 

     // Convert byte[] to Base64 String 
     string base64String = Convert.ToBase64String(imageBytes); 
     return base64String; 
     } 
    } 

回答

0

我建议开沟HttpWebRequest有利于WebClient。另外,如果您使用application/x-www-form-urlencodedcontent-type发送,则服务器将期望发布的数据与key1=value1&key2=value2的格式匹配。

// sending image to server as base 64 string 
string imageBase64String = "YTM0NZomIzI2OTsmIzM0NTueYQ..."; 
using (WebClient client = new WebClient()) 
{ 
    var values = new NameValueCollection(); 
    values.Add("image", imageBase64String); 
    client.UploadValues("http://192.168.1.2/", values); 
} 

同样的事情,但使用WebHttpRequest

string imageBase64String = "YTM0NZomIzI2OTsmIzM0NTueYQ..."; 
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://192.168.1.2/"); 
webRequest.ContentType = "application/x-www-form-urlencoded"; 
webRequest.Method = "POST"; 
string formPostString = "image=" + HttpUtility.UrlEncode(imageBase64String); 
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(formPostString); 
webRequest.ContentLength = buffer.Length; 
using (Stream webStream = webRequest.GetRequestStream()) 
{ 
    webStream.Write(buffer, 0, buffer.Length); 
} 

然后,您可以处理使用HttpRequest对象服务器端发送的图像。

string imageBase64String = HttpContext.Current.Request.Form["image"]; 
+2

[WebClient.UploadValues](http://msdn.microsoft.com/en-us/library/9w7b4fz7.aspx)是即使对于' “应用程序/ x WWW的形式进行了urlencoded”'有效载荷更好因为它会设置标题并为您编写URL编码。 – dtb 2010-09-18 17:56:09

+0

@dtb:很好的提示知道。谢谢。 – tidwall 2010-09-18 19:26:47

+0

事情是我需要从服务器得到响应。因此我使用了WebReuqest。我被指示使用HTTP Post并使用HTTP Post发送ASCII字符串,因此如何做到这一点? “ContentType”应该是什么?我并不熟悉ContentType实际是什么,所以我只是把“application/x-www-form-urlencoded” – Robogal 2010-09-19 05:47:59