我目前正在以字节数组的形式发送图像数据。但是,我希望以ASCII字符串形式发送它。如何在c#中使用HTTP POST从客户端向服务器发送ASCII字符串?
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 :(得分:0)
我建议放弃HttpWebRequest
支持WebClient
。此外,如果您使用content-type
application/x-www-form-urlencoded
发送,则服务器将期望发布的数据与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"];