在商店应用程序中通过HTTP POST发送字节数组

时间:2014-05-07 13:11:38

标签: c# http windows-store-apps bytearray

我正试图通过Windows商店应用程序的HTTP帖子将一些图像+一些元数据发送到服务器,但在尝试实际包含帖子中的数据时卡住了。由于商店应用API的更改,无法按照您在Windows窗体应用程序或类似应用程序中完成此操作的方式完成。

我收到错误。

cannot convert source type byte[] to target type System.Net.Http.httpContent

现在这显然是因为它有两种不能隐式投射的不同类型,但它基本上是我希望能够做到的。如何将我的字节数组数据转换为httpContent类型,以便将其包含在以下调用中

httpClient.PostAsync(Uri uri,HttpContent content);

这是我的完整上传方法:

async private Task UploadPhotos(List<Photo> photoCollection, string recipient, string format)
    {
        PhotoDataGroupDTO photoGroupDTO = PhotoSessionMapper.Map(photoCollection);

        try
        {
            var client = new HttpClient();
            client.MaxResponseContentBufferSize = 256000;
            client.DefaultRequestHeaders.Add("Upload", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

            // POST action_begin
            const string actionBeginUri = "http://localhost:51139/PhotoService.axd?action=Begin";
            HttpResponseMessage response = await client.GetAsync(actionBeginUri);
            response.EnsureSuccessStatusCode();
            string responseBodyAsText = await response.Content.ReadAsStringAsync();
            string id = responseBodyAsText;
            ////

            // POST action_upload
            Uri actionUploadUri = new Uri("http://localhost:51139/PhotoService.axd?action=Upload&brand={0}&id={1}&name={2}.jpg");

            var metaData = new Dictionary<string, string>()
            {
                {"Id", id},
                {"Brand", "M3rror"}, //TODO: Denne tekst skal komme fra en konfigurationsfil.
                {"Format", format},
                {"Recipient", recipient}
            };

            string stringData = "";
            foreach (string key in metaData.Keys)
            {
                string value;
                metaData.TryGetValue(key, out value);
                stringData += key + "=" + value + ",";
            }

            UTF8Encoding encoding = new UTF8Encoding();
            byte[] byteData = encoding.GetBytes(stringData);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, actionUploadUri);

            // send meta data
            // TODO get byte data in as content
            HttpContent metaDataContent = byteData;
            HttpResponseMessage actionUploadResponse = await client.PostAsync(actionUploadUri, metaDataContent);

            actionUploadResponse.EnsureSuccessStatusCode();
            responseBodyAsText = await actionUploadResponse.Content.ReadAsStringAsync();

            // send photos
            // TODO get byte data in as content
            foreach (byte[] imageData in photoGroupDTO.PhotosData)
            {
                HttpContent imageContent = imageData;
                actionUploadResponse = await client.PostAsync(actionUploadUri, imageContent);
                actionUploadResponse.EnsureSuccessStatusCode();
                responseBodyAsText = await actionUploadResponse.Content.ReadAsStringAsync();
            }                
            ////

            // POST action_complete
            const string actionCompleteUri = "http://localhost:51139/PhotoService.axd?action=Complete";
            HttpResponseMessage actionCompleteResponse = await client.GetAsync(actionCompleteUri);
            actionCompleteResponse.EnsureSuccessStatusCode();
            responseBodyAsText = await actionCompleteResponse.Content.ReadAsStringAsync();
            ////
        }

        catch (HttpRequestException e)
        {
        }
        catch (Exception e)
        {
            Debug.WriteLine(e.ToString());
        }
    }

3 个答案:

答案 0 :(得分:38)

使用System.Net.Http.ByteArrayContent会更直接。 E.g:

// Converting byte[] into System.Net.Http.HttpContent.
byte[] data = new byte[] { 1, 2, 3, 4, 5};
ByteArrayContent byteContent = new ByteArrayContent(data);
HttpResponseMessage reponse = await client.PostAsync(uri, byteContent);

对于仅使用特定文本编码的文本:

// Convert string into System.Net.Http.HttpContent using UTF-8 encoding.
StringContent stringContent = new StringContent(
    "blah blah",
    System.Text.Encoding.UTF8);
HttpResponseMessage reponse = await client.PostAsync(uri, stringContent);

或者如上所述,对于使用multipart / form-data的文本和图像:

// Send binary data and string data in a single request.
MultipartFormDataContent multipartContent = new MultipartFormDataContent();
multipartContent.Add(byteContent);
multipartContent.Add(stringContent);
HttpResponseMessage reponse = await client.PostAsync(uri, multipartContent);

答案 1 :(得分:11)

您需要将字节数组包装在HttpContent类型中。

如果您使用的是System,Net.Http.HttpClient:

HttpContent metaDataContent = new ByteArrayContent(byteData);

如果您使用首选的Windows.Web.Http.HttpClient:

Stream stream = new MemoryStream(byteData);
HttpContent metaDataContent = new HttpStreamContent(stream.AsInputStream());

答案 2 :(得分:0)

您正在寻找的概念称为Serialization。序列化意味着准备您的数据(可能是异构的,没有预定义的结构)用于存储或传输。然后,当您需要再次使用数据时,执行相反的操作,反序列化并返回原始数据结构。上面的链接显示了一些如何在C#中完成此操作的方法。