Un poco de Java

Enero 27, 2009 :: Posted by - Emilio Torrens :: Category -

Tenia algunos problemas con un cliente que consumía un servicio mío mandando XML por HTTP-POST, el IIS bloqueaba sus peticiones y no había manera de ver porque, así que me hice un cliente exacto al suyo para poder debugear el tema.

Por si os sirve, aquí os dejo el código Java:

import java.io.*;
import java.net.*;
import java.util.Properties;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;

public static String POST(String sURL, String sData)
   {
        try
        {
            URL url = new URL(sURL);
            URLConnection urlc = url.openConnection();
            urlc.setRequestProperty("Content-Type",    "application/x-www-form-urlencoded");
            urlc.setDoOutput(true);
            OutputStream os = urlc.getOutputStream();

            byte[] postData = sData.getBytes();
            os.write(postData);

            os.flush();
            os.close();

            InputStream is = urlc.getInputStream();

            return parseISToString(is);

        }
        catch(IOException ex)
        {
            return ex.getMessage();
        }
   }

   public static String parseISToString(java.io.InputStream is)
   {

        java.io.DataInputStream din = new java.io.DataInputStream(is);
        StringBuffer sb = new StringBuffer();

        try
        {
            String line = null;
            while((line=din.readLine()) != null)
            {
                sb.append(line+"\n");
            }
            return sb.toString();
        }
        catch(Exception ex)
        {
            return ex.getMessage();
        }

   }

Obtener los datos XML de un Documento SOAP

Enero 09, 2009 :: Posted by - Emilio Torrens :: Category - , ,

Mas de mi servicio "impersonal" …

Resulta que ahora también recibe documentos SOAP, así que tengo que extraer los datos del mensaje SOAP con este código:

private XmlDocument GetSOAPBody(XmlDocument xmlSoap)
    {

              const string SOAP_NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope/";
              XmlNodeList nodes = xmlSoap.GetElementsByTagName("Body", SOAP_NAMESPACE);

          if (nodes.Count == 0) return xmlSoap;

          XmlElement body = (XmlElement)nodes.Item(0);

          nodes = body.ChildNodes;
          for (int i = 0; i < nodes.Count; i++)
          {
              XmlNode node = nodes.Item(i);
              if (node is XmlElement)
              {
                  xmlSoap = new XmlDocument();
                  xmlSoap.LoadXml(node.OuterXml);
                  IsSOAP = true;
                  return xmlSoap;
              }
          }

          return xmlSoap;
      }  

Funciona bastante bien, ahora estoy con el de generar las respuestas de OK y de Error, ya lo publicare :)