HttpRequestMessage发送数据分块

时间:2018-08-13 08:32:06

标签: c# http upload chunked

我编写了以下代码,并希望在JSON字符串中发送图片,这对于HTTP-Body〜9MB来说太大了。现在,我想发送分块的JSON,有没有一种方法可以发送用HttpRequestMessage分块的数据?

我找到了此链接,但不知道他在做什么:httpwebrequest-chunked-async-post

public string Request(string resource, string method, string contentType, string json)
    {
        try
        {
            using (var client = new HttpClient())
            {
                var request = new HttpRequestMessage(new HttpMethod(method), resource);
                request.Content = new StringContent(json, Encoding.UTF8, contentType);

                var response = client.SendAsync(request).Result;
                if (!response.IsSuccessStatusCode)
                {
                    return null;
                }

                var result = string.Empty;
                using (var resultStream = response.Content.ReadAsStreamAsync().Result)
                {
                    var bytes = new byte[resultStream.Length];
                    resultStream.Read(bytes, 0, bytes.Length);

                    result = System.Text.Encoding.Default.GetString(bytes);
                }

                return result;
            }
        }
        catch (WebException e)
        {
            var response = e.Response;
            if (response == null)
                return null;

            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                var error = reader.ReadToEnd();
                Log.Error($"[Rest.RunAction] {error}");
            }

            return null;
        }
    }

0 个答案:

没有答案