2014-09-18 2 views
0

웹 서비스를 사용하여 사진을 쿼리 할 수있는 서버가 있습니다. 서버를 유지 관리하는 사람은 Java 개발자이지만 SDK를 사용하여 현재 실행중인 응용 프로그램과 통합 할 때 dotNET을 사용하여 서버를 쿼리 할 수 ​​있어야하며 dotNET을 지원할 수 없거나 지원할 수 없습니다.여러 부분으로 구성된 HttpWebResponse

이 사진에 대한 내 요청 (필요한 인증서를 참고)입니다 : -

private WebResponse Request() 
{ 
    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(Validate); 
    X509Certificate certificate = X509Certificate.CreateFromCertFile("wmbuat.crt"); 

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(server.Text); 
    request.Headers.Add("SOAP:Action"); 
    request.ContentType = "text/xml"; 
    request.Accept = "text/xml"; 
    request.Method = "POST"; 
    request.ClientCertificates.Add(certificate); 

    GetXml().Save(request.GetRequestStream()); 
    return request.GetResponse(); 
} 

private static Boolean Validate(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) 
{ 
    return true; 
} 

내가 서버에게 어떤 드라마를 조회 할 수 있지만, HttpWebResponse 클래스가 하나 개의 스트림의 두 부분으로 포함 -는 XML 부분을 포함하는 정보를 사진 및 JPEG의 이진 부분에 대한 정보를 제공합니다. 예를 들어 : -

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

<NS1:Envelope xmlns:NS1="http://schemas.xmlsoap.org/soap/envelope/">...</NS1:Envelope> 
--WMBMIME2Boundaryurn_uuid_C123 
Content-Type: application/octet-stream 
Content-Transfer-Encoding: binary 
Content-ID: <987> 

yoya..JFIF... 

나는 여기에 관련된에 대한 몇 가지 질문을 본 적이 있지만 나는이 라이브러리와 인증서를 사용할 수 있도록하지 않는 것. 출력 스트림을 래핑하여 부품을 별도의 객체로 가져 오는 간단한 방법이 있습니까? String과 byte [] 만 있으면 좋겠고 XML과 Image로 직접 변환 할 수 있습니다.

나는에서는 StreamReader를 사용하여 이진 데이터는 다음 파일에 원래 스트림에서 나머지를 읽기 시작하는 곳이다 번째 빈 줄, 최대 읽기 시도했지만 문제가 해결되지 않은 : -/

어떤 도움이라도 대단히 감사하겠습니다.

감사합니다.

답변

0

이와 비슷한 것을 달성하려는 다른 모든 사람들에게이 개념 증명을 위해 약간의 해결 방법을 제시했습니다. 그것은 가장 효율적인 코드 아니지만, 내가 때 버튼을 처음 실행 :-)

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.IO; 
using System.Linq; 
using System.Net; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Xml; 

namespace COPS_Photo_Viewer 
{ 
    public partial class CPV : Form 
    { 
     public CPV() 
     { 
      InitializeComponent(); 

      textIP.Text = Dns.GetHostAddresses(Dns.GetHostName())[0].MapToIPv4().ToString(); 
      textID.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name; 
      textMachine.Text = Dns.GetHostName(); 
      textApplication.Text = Application.ProductName; 
     } 

     private Image ExtractImage(byte[] binary) 
     { 
      int start = 0; 
      for (; start < binary.Length; ++start) 
       if (((char)binary[start]) == 'ÿ') 
        break; 

      byte[] image = new byte[binary.Length - start]; 
      for (int index = start; index < binary.Length; ++index) 
       image[index - start] = binary[index]; 

      return Bitmap.FromStream(new MemoryStream(image)); 
     } 

     private void GetImage(Object sender, EventArgs args) 
     { 
      WebResponse response = Request(); 
      byte[] input = ReadStream(response.GetResponseStream()); 
      photograph.Image = ExtractImage(input); 
     } 

     private XmlDocument GetXml() 
     { 
      XmlDocument xml = new XmlDocument(); 
      xml.LoadXml(...); 
      return xml; 
     } 

     private byte[] ReadStream(Stream stream) 
     { 
      Queue<byte> input = new Queue<byte>(); 
      byte[] buffer = new byte[1]; 

      for (int read = stream.ReadByte(); read >= 0; read = stream.ReadByte()) 
       input.Enqueue((byte)read); 

      return input.ToArray<byte>(); 
     } 

     private WebResponse Request() 
     { 
      ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(Validate); 
      System.Security.Cryptography.X509Certificates.X509Certificate certificate = 
      System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile("wmbuat.crt"); 

      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(textURL.Text); 
      request.Headers.Add("SOAP:Action"); 
      request.ContentType = "text/xml"; 
      request.Accept = "text/xml"; 
      request.Method = "POST"; 
      request.ClientCertificates.Add(certificate); 

      GetXml().Save(request.GetRequestStream()); 
      return request.GetResponse(); 
     } 

     private static Boolean Validate(Object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors) 
     { 
      return true; 
     } 
    } 
} 

된 GetImage을 끝내야 한 다른 모든 것들 사이에-을 개선하는 작업을하는 동안 단기적으로 일을 얻는다 양식의 결과가 나오면 응답 스트림을 바이트 배열로 바꾼 다음 "ÿ"의 첫 번째 인스턴스 (JPEG의 시작 부분에만 표시됨)를 검색 한 다음 MemoryStream으로 배열을 변환 한 다음 이미지로 변환합니다.

큐에 한 번에 한 바이트 씩 읽는 것이 가장 좋지는 않지만 다행스럽게도이 작업은 네트워크를 통해 실행되므로 (최소한이 초기 개발 단계에서) 문제가되지 않으며 사진이 즉시로드됩니다.

0

사용중인 클라이언트, 요청 및 응답 클래스는 System.Net 네임 스페이스에 있습니다.이 네임 스페이스는 System.Net.Http 네임 스페이스의 최신 클래스보다 약간 적게 사용됩니다. 새로운 기능과 마찬가지로 설명서와 예제도 적지 만이 경우에는 "Microsoft WebAPI Framework"와 함께 제공되는 클라이언트 클래스를 사용하면 도움이 될 것입니다.

특히, WebAPI 프레임 워크의 응답 클래스는 HttpResponseMessage라고하며 당신은 여기 다른 네임 스페이스에 대한 자세한 설명서를 찾을 수 있습니다

HttpResponseMessage response = ... 
HttpContent content = response.Content; 
if(content is MultipartContent) 
{ 
    // loop through parts 
} 

속성이 있습니다

http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

하나 deal-breaker는 이전 버전의 .NET에있을 수 있습니다. 필자는 WebAPI 2가 4.5 버전의 최신 버전을 필요로한다고 믿지만 버전 4 버전을 찾을 수 있습니다. 이전 버전을 사용하지는 않았지만 다중 컨텐트 부분으로 구분하기 위해 수행하는 구문 분석은 비 상식입니다. 하찮은.

+0

안녕하세요, 고마워요. 네가 말했듯이 dotNET 4.0에 접근 할 수있다. 기술적으로 대부분의 PC가 우리 회사의 3.5에서 실행되지만 필요에 따라 4.0으로 업그레이드 할 수있다. 우리는 여전히 XP를 사용하고 있기 때문에 4.5를 설치할 수 없습니다. – SignalOne

+0

yikes, ok 행운을 빌어 HTTP mime 부분을 파싱하는 좋은 방법을 찾은 후, 거기에 튜토리얼이있을 것이라고 확신하지만 거기에는 많은 ich가 있습니다. – welegan

관련 문제