Мыло запрос с вложением через - HttpWebRequest - PullRequest
0 голосов
/ 08 октября 2018

Я получаю сообщение об ошибке при вызове простого веб-сервиса через Soap-конверт через HttpWebRequest, состоящий из нескольких частей.

Базовое намерение - « Запрос мыла вместе с вложением » (MTOM).

Запрашиваемые части для HttpWebRequest:


--MIMEBoundaryurn_uuid_d12fdc05-2031-4701-a2f9-3f65228234af

Content-Type: application/xop+xml; charset=UTF-8; type=text/xml; charset=UTF-8; 

Content-ID: <0.urn:uuid:e4987c60-a0e4-43b4-8017-a8263604a4e3>

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/"><soapenv:Header/><soapenv:Body><tem:GetFile><tem:filename>abc.txt</tem:filename><tem:fileContents><inc:Include href=cid:57237107-66b0-4eac-bd9d-9c08ad02008b xmlns:inc="http://www.w3.org/2004/08/xop/include"/></tem:fileContents></tem:GetFile></soapenv:Body></soapenv:Envelope>

--MIMEBoundaryurn_uuid_d12fdc05-2031-4701-a2f9-3f65228234af

Content-Type: text/xml

Content-Transfer-Encoding: binary

Content-ID: <57237107-66b0-4eac-bd9d-9c08ad02008b>

Content-Disposition: attachment; name=abc.txt; filename=abc.txt 

--MIMEBoundaryurn_uuid_d12fdc05-2031-4701-a2f9-3f65228234af--

Вот мой пример кода:

private void uploadFile()
        {
            string endPoint = @"http://localhost:51027/Service1.svc";
            string action = "http://tempuri.org/IService1/GetFile";
            string boundary = "MIMEBoundaryurn_uuid_";
            string CRLF = "\r\n";
            string uuid = System.Guid.NewGuid().ToString();
            string reqUUID = System.Guid.NewGuid().ToString();
            string attchmtUUID = System.Guid.NewGuid().ToString();
            HttpWebResponse httpResp = null;

            //Create the HTTP request and set the headers
            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(endPoint);
            httpRequest.Headers.Add("UserAgent", "Apache-HttpClient");
            httpRequest.Headers.Add("MIME-Version", "1.0");
            httpRequest.Headers.Add("SOAPAction", action);
            httpRequest.ContentType = "multipart/related; boundary="    + boundary + uuid + "; type=\"application/xop+xml\"; start=\"<0." + "urn:uuid:" + reqUUID + ">\"; start-info=\"text/xml\"";

            //Set the method to POST
            httpRequest.Method = "POST";

            //Read the gzip file as a byte array
            FileStream fs = File.OpenRead(attachmentFilePath);
            byte[] attachment = new byte[fs.Length];
            fs.Read(attachment, 0, attachment.Length);
            fs.Close();

            //Form the request string
            string uploadFileRequest = "--" + boundary + uuid + CRLF
                            + "Content-Type: application/xop+xml; charset=UTF-8; type=text/xml; charset=UTF-8; " + CRLF
                            + "Content-ID: <0.urn:uuid:" + reqUUID + ">" + CRLF + CRLF
                            + @"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:tem=""http://tempuri.org/""><soapenv:Header/><soapenv:Body><tem:GetFile><!--Optional:--><tem:filename>abc.txt</tem:filename><!--Optional:--><tem:fileContents><inc:Include href=cid:" + attchmtUUID + @" xmlns:inc=""http://www.w3.org/2004/08/xop/include""/></tem:fileContents></tem:GetFile></soapenv:Body></soapenv:Envelope>"
                            + CRLF + "--" + boundary + uuid + CRLF
                            + "Content-Type: text/xml" + CRLF
                            + "Content-Transfer-Encoding: binary" + CRLF
                            + "Content-ID: <" + attchmtUUID + ">" + CRLF + CRLF
                            + @"Content-Disposition: attachment; name=abc.txt; filename=abc.txt" + CRLF + CRLF;

            string strReq2 = CRLF + "--" + boundary + uuid + "--" + CRLF;

            byte[] postDataBytes2 = System.Text.Encoding.UTF8.GetBytes(strReq2);

            //Convert the string to a byte array
            byte[] postDataBytes1 = System.Text.Encoding.UTF8.GetBytes(uploadFileRequest);

            int len = postDataBytes1.Length + postDataBytes2.Length + attachment.Length;
            httpRequest.ContentLength = len;

            //Post the request
            System.IO.Stream requestStream = httpRequest.GetRequestStream();
            requestStream.Write(postDataBytes1, 0, postDataBytes1.Length);
            requestStream.Write(attachment, 0, attachment.Length);
            requestStream.Write(postDataBytes2, 0, postDataBytes2.Length);
            requestStream.Close(); 

            string response;

            // Get response and write to console
            try
            {
                httpResp = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException e)
            {
                using (WebResponse respons = e.Response)
                {
                    HttpWebResponse httpResponse = (HttpWebResponse)respons;
                    Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
                    using (Stream data = respons.GetResponseStream())
                    using (var reader = new StreamReader(data))
                    {
                        string text = reader.ReadToEnd();
                        Console.WriteLine(text);
                    }
                }
            }

            StreamReader responseReader = new StreamReader(httpResp.GetResponseStream(), Encoding.UTF8);
            response = responseReader.ReadToEnd();
            httpResp.Close(); 

            Console.WriteLine(response);
        }

Во время компиляции, когда я прихожу к выписке: httpResp = (HttpWebResponse) httpRequest.GetResponse ();

Возвращает обратно httpResp Код ошибки 400. Неверный запрос .

...