【发布时间】:2014-09-09 07:58:18
【问题描述】:
我得到一个像这样的多部分/混合(带有一个 JSON 对象和一个文件),作为我调用 Web 服务时的响应:
"--Boundary_9_15033478_1405613164044\r\n
Content-Type: application/json
\r\n\r\n{\"docId\":9007492,\"protId\":200,\"protNum\":\"0002084B14\",\"protDate\":\"Wed Jul 16 00:00:00 EEST 2014\",\"categoryId\":1000,\"desc\":\"ѥ????ⷞ ��ƣ䲜��",\"linkNum\":\"ư1\\/00005545\",\"flag1\":\"\",\"flag2\":\"\",\"flag3\":\"\",\"flag4\":\"\",\"stsId\":1,\"stsDesc\":\"WS04: Check Layer I - OK\",\"wsDataList\":[],\"fileName\":\"WsTestToolkitMain.jpg\"}\r\n--Boundary_9_15033478_1405613164044\r\n
Content-Type: application/octet-stream
\r\n\r\n????\0JFIF\0\0`\0`\0\0??\0C\0\a\a\a\a\a\a\b\t\v\t\b\b\n\b\a\a\n\r\n\n\v\f\f\f
...
...
...
??\n?$??\0???????\r\n--Boundary_9_15033478_1405613164044--\r\n"
我得到它的方法是获取响应流(HttpWebRequest),然后使用 UTF-8 对其进行解码。这给了我上面的字符串。 问题是如何获取 JSON 并(更重要的是)保存文件?
我尝试更改(因为它们用于 multipart/form-data 而不是 multipart/mixed)this 和 this 但我无法获取文件,可能是因为它的 Content-Type 是 application/octet -流。这是什么不起作用,文件在 Windows 中显示为损坏/损坏:
// Read the stream into a byte array
byte[] data = ToByteArray(stream);//Source
string content = encoding.GetString(data);
int contentLength = content.Length;//Length
byte[] fileData = new byte[contentLength];//Destination
Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength);
this.FileContents = fileData;
File.WriteAllBytes("G:\\" + parser.Filename, parser.FileContents);
更新: 跟随 Anton Tykhyy 的回答(谢谢!),但是当
var multipart = await content.ReadAsMultipartAsync () ;
提供的“HttpContent”实例无效。它没有内容类型标头值。 “HttpContent”实例必须具有以“multipart/”开头的内容类型标头。
我尝试在之前添加这一行
content.Headers.Add("Content-Type", "multipart/mixed");
但现在我遇到了另一个错误(我也不太明白)
提供的“HttpContent”实例无效。它没有带有“边界”参数的“多部分”内容类型标头。
更新 2: 找到了,我只需要这样做:
var content = new StreamContent(httpResponse.GetResponseStream());
content.Headers.Add("Content-Type", httpResponse.ContentType);
【问题讨论】: