我需要解析一个Web API响应数据,其中包含一个JSON响应和一个纯文本图像。我试图用--Boundary分割此响应。拆分后,我可以轻松解析JSON数据,但无法生成图像文件。我也尝试在线将Base64纯文本生成到Image Generator,但是失败了。
响应流如下所示:
--BOUNDARY
Content-Type: application/json; name="Live_Info"
json data
--BOUNDARY
Content-Type: image/jpeg; name="Live_data"
Live image plain text data
ex: ÿØÿÛ C
#%$""!&+7/&)4)!"0A149;>>>%.DIC<H7=>;ÿÛ C
;("(;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ÿÀ
--BOUNDARY
这是我尝试过的代码
HttpWebRequest webrequestlive =
(HttpWebRequest)WebRequest.Create(request_uri_live);
try
{
webrequestlive.KeepAlive = false;
HttpWebResponse webresponselive =
(HttpWebResponse)webrequestlive.GetResponse();
if (webresponselive.StatusCode == HttpStatusCode.OK)
{
Stream stream = webresponselive.GetResponseStream();
StreamReader reader = new StreamReader(stream);
var html_body = reader.ReadToEnd();
byte[] imageBytes;
string[] split = html_body.Split(new string[] { "--
BOUNDARY\r\n" }, StringSplitOptions.None);
LiveImageRetrievalCommandJOSNParser.Rootobject obj1 =
JsonConvert.DeserializeObject<
LiveImageRetrievalCommandJOSNParser.Rootobject> (split[0]);
byte[] imagedata = Encoding.UTF8.GetBytes(split[2]);
using (var imagestream = new MemoryStream(imagedata ))
{
using (BinaryReader br = new
BinaryReader(imagestream))
{
imageBytes = br.ReadBytes(500000);
br.Close();
}
//Image LiveImage = Image.FromStream(imagestream);
Image liveimage = (Bitmap)((new
ImageConverter()).ConvertFrom(imageBytes));
liveIMage.Image = liveimage;
}
stream.Close();
webresponselive.Close();
}
else
{
webrequestlive.Abort();
Thread.Sleep(5000);
ErrorLog("Bad Request for getting Live Image");
}
}
catch (Exception exer)
{
webrequestlive.Abort();
Thread.Sleep(5000);
ErrorLog(exer.Message);
}
解析后,此流的实际结果是JSON数据和图片。