[英]How to send image in HttpClient SendRequestAsync
I am using Windows.Web.Http instead of System and I am trying to send an image. 我正在使用Windows.Web.Http而不是System,并且正在尝试发送图像。
My sample code: 我的示例代码:
Dictionary<string, object> requestDictionary;
HttpClient httpClient = new HttpClient();
HttpRequestMessage re = new HttpRequestMessage();
HttpResponseMessage response;
re.Method = HttpMethod.Post;
re.RequestUri = url;
string content_type = "application/json";
string req_data = JsonConvert.SerializeObject(requestDictionary);
re.Content = new HttpStringContent(req_data, UnicodeEncoding.Utf8, content_type);
response = await httpClient.SendRequestAsync(re);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
httpClient.Dispose();
httpClient=null;
In this case my requestDictionary will be some thing like 在这种情况下,我的requestDictionary会像
requestDictionary.Add("Image", filename);
requestDictionary.Add("description", some_description);
Someone please help me to achieve this. 有人请帮助我实现这一目标。
By using .Net 4.5 (or by adding the Microsoft.Net.Http package from NuGet) there is an easier way to do this: 通过使用.Net 4.5(或通过从NuGet添加Microsoft.Net.Http包),有一种更简单的方法:
private string Upload(string actionUrl, string paramString, byte[] paramFileBytes)
{
HttpContent stringContent = new StringContent(paramString);
HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(stringContent, "paramter");
formData.Add(bytesContent, "image");
var response = client.PostAsync(actionUrl, formData).Result;
if (!response.IsSuccessStatusCode)
{
return null;
}
return response.Content.ReadAsStringAsync().Result;
}
}
If you prefer to use a stream instead of a byte-array you can easily do this, by just using new StreamContent()
instead of new ByteArrayContent()
. 如果您更喜欢使用流而不是字节数组,则可以通过使用new StreamContent()
而不是new ByteArrayContent()
轻松地做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.