目录
1.确保自建的本地Web服务正常运行
2.确保网络畅通
3.请求体参数img的创建
用Bitmap-转-内存流-转-字节数组-转-Base64编码字符串-转-Web编码
4.实例代码
//打开本地文件,建立Bitmap对象
Bitmap image = new Bitmap("@"D:\image.png"");
//创建内存流
Stream imageStream = new System.IO.MemoryStream();
//Bitmap写入imageStream内存流
image.Save(imageStream, ImageFormat.Png);
//内存指针跳转到开头
imageStream.Seek(0, SeekOrigin.Begin);
//创建缓存字节数组对象
byte[] buff = new byte[imageStream.Length];
//流读取转为字节数组
imageStream.Read(buff, 0, buff.Length);
//创建HttpClient对象
HttpClient httpClient = new HttpClient();
//字节数组Base64编码转为String,Web编码避免字符歧义,创建成请求字符串
string img = HttpUtility.UrlEncode(Convert.ToBase64String(buff));
//创建HttpBody,写入请求参数,请求内容格式为表单格式
HttpContent content = new StringContent($"img={img}&is_draw=0");
//添加请求头,标注Body内容为x-www-form-urlencoded(表单格式)
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
//得到响应的消息
HttpResponseMessage message = httpClient.PostAsync("http://192.168.2.244:8089/api/tr-run/", content).GetAwaiter().GetResult();
//得到响应结果,解析Unicode编码
string data = Regex.Unescape(message.Content.ReadAsStringAsync().GetAwaiter().GetResult());