我需要帮助从网络服务中检索图片。这是一个GET请求。
目前我正在检索响应并且我能够将其转换为字节数组,这就是我想要的,但字节数组会崩溃应用程序,因此我认为内容设置不正确
我尝试使用以下方式设置响应内容:
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = filename };
即使我的猜测是它设置不正确,或者它在requestHeader中已经设置错误。
有什么想法吗?
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseurl.uri);
client.DefaultRequestHeaders.Add("x-access-token", sessionToken);
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("image/jpeg")
);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "");
try
{
Task<HttpResponseMessage> getResponse = client.SendAsync(request);
HttpResponseMessage response = new HttpResponseMessage();
response = await getResponse;
//1. response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = filename };
//2. response.Content.Headers.ContentType =
//new MediaTypeHeaderValue("image/jpeg");//("application/octet-stream");
byte[] mybytearray = null;
if (response.IsSuccessStatusCode)
{
//3.
mybytearray = response.Content.ReadAsByteArrayAsync().Result;
}
var responseJsonString = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(responseJsonString);
System.Diagnostics.Debug.WriteLine("GetReportImage ReponseCode: " + response.StatusCode);
return mybytearray;//{byte[5893197]}
}
catch (Exception ex)
{
string message = ex.Message;
return null;
}
}
答案 0 :(得分:0)
您可以发送图片的有效字节数组作为HttpContent
HttpContent contentPost = new
StringContent(JsonConvert.SerializeObject(YourByteArray), Encoding.UTF8,
"application/json");
反序列化结果后,您可以检索字节数组,保存与jpeg或任何其他格式相同。
byte[] imageByteArray = byteArray;
using(Image image = Image.FromStream(new MemoryStream(imageByteArray)))
{
image.Save("NewImage.jpg", ImageFormat.Jpeg);
}