如何发送图像在HttpClient SendRequestAsync

本文关键字:HttpClient SendRequestAsync 图像 何发送 | 更新日期: 2023-09-27 18:07:17

我正在使用Windows.Web.Http而不是System,我正在尝试发送图像。

我的示例代码:
    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;

在本例中,我的requestDictionary将是类似

的内容
    requestDictionary.Add("Image", filename);
    requestDictionary.Add("description", some_description);

谁来帮我实现这个

如何发送图像在HttpClient SendRequestAsync

通过使用。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;
    }
} 

如果你更喜欢使用流而不是字节数组,你可以很容易地做到这一点,只需使用new StreamContent()而不是new ByteArrayContent()