从 SOAP 响应获取附件并保存文件

问题描述 投票:0回答:2

我正在使用 Web 服务,它以带有附件的 SOAP 形式给出响应。 我使用 PostMan 捕获的响应是

--MIMEBoundaryurn_uuid_C455EAC131FBC506CE1521805985220
Content-Type: text/xml; charset=UTF-8
Content-Transfer-Encoding: 8bit
Content-ID: <0.urn:uuid:[email protected]>

<?xml version='1.0' encoding='UTF-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><ns:downloadDocInFileResponse xmlns:ns="http://provider.ws.jts.omni.newgen.com"><ns:return><swa:fileName xmlns:swa="http://provider.ws.jts.omni.newgen.com"><swa:graph>urn:uuid:C455EAC131FBC506CE1521805985219</swa:graph><swa:message>file download on server successfully</swa:message></swa:fileName></ns:return></ns:downloadDocInFileResponse></soapenv:Body></soapenv:Envelope>
--MIMEBoundaryurn_uuid_C455EAC131FBC506CE1521805985220
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
Content-ID: <urn:uuid:C455EAC131FBC506CE1521805985219>

II*----binary content----

我的代码是

    using (WebResponse response = request.GetResponse())
                {
                    using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                    {
                        string soapResult = rd.ReadToEnd();
                        retVal = soapResult;
                        byte[] temp = Encoding.ASCII.GetBytes(soapResult);
                    }
                }
 var binaryString = ToBinary(ConvertToByteArray(retVal, Encoding.ASCII));

            byte[] bytes = Convert.FromBase64String(binaryString);
            string path = HttpContext.Current.Server.MapPath("/test.pdf");

            File.WriteAllBytes(path, bytes);

但是文件已损坏。

c# web-services soap attachment
2个回答
3
投票

完成此工作后,我在 MultipartMemoryStreamProvider 的帮助下找到了解决方案

 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {

           String retVal = readMultipart(response).Result;
        }

async static Task<string> readMultipart(HttpWebResponse httpResponse)
        {
            var content = new StreamContent(httpResponse.GetResponseStream());
            content.Headers.Add("Content-Type", httpResponse.ContentType);


            MultipartMemoryStreamProvider multipart = new MultipartMemoryStreamProvider();
            Task.Factory.StartNew(() => multipart = content.ReadAsMultipartAsync().Result,
               CancellationToken.None,
               TaskCreationOptions.LongRunning, // guarantees separate thread
               TaskScheduler.Default)
               .Wait();
            String filename = "";
            String json = await multipart.Contents[0].ReadAsStringAsync();


            string path = HttpContext.Current.Server.MapPath("/test.jpeg");
            byte[] fileData = multipart.Contents[1].ReadAsByteArrayAsync().Result;
            System.IO.File.WriteAllBytes(path, fileData);
            return json;
        }

0
投票

它也使用 MultipartMemoryStreamProvider 对我有用。 我正在开发 C# 4.6.1

    public static async Task GetFIle(string xmlDownloadASO)
    {
        try
        {
            string serviceUrl = "https://xxxxxxxxx/xxxx/DownloadFilesWS";

            using (HttpClient client = new HttpClient())
            {
                HttpContent content = new StringContent(xmlDownloadASO, System.Text.Encoding.UTF8, "application/octet-stream");
                HttpResponseMessage response = await client.PostAsync(serviceUrl, content);

                if (response.IsSuccessStatusCode)
                {
                    await ReadMultipart(response.Content);
                }
                else
                {
                    Console.WriteLine($"Error: {response.StatusCode}");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception : " + ex.Message);
        }
    }
    async static Task ReadMultipart(HttpContent content)
    {
        try
        {
            MultipartMemoryStreamProvider multipart = await content.ReadAsMultipartAsync();

            String filename = "testxxxxx.zip";
            String json = await multipart.Contents[0].ReadAsStringAsync();

            string path = "C:/temp/"+filename;
            byte[] fileData = await multipart.Contents[1].ReadAsByteArrayAsync();
            System.IO.File.WriteAllBytes(path, fileData);

            Console.WriteLine("JSON: " + json);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exceção ao processar resposta multipart: " + ex.Message);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.