Hello,

I am Using Apache SOAP to access Webservers that require HTTP 401 
Authentication.

From my point of view it is a good idea to let java.net.Authenticator
do the work of asking the User for credentials.

Benefit 1: via java.net.Authenticator org.apache.soap.util.net.HTTPUtils
can not only use Basic auth but also NTLM, Kerberos an everything
the underlying JRE provides through java.net.Authenticator.

Benefit 2: The Proxy configuration of underlying JRE is used.

In Implematation of org.apache.soap.util.net.HTTPUtils 
that means switch using of java.lang.Socket
to using  of java.lang.URLConnection, because that anables the
Software to use the credentials of java.net.Authenticator.

Find attached my "first shot" Reimplementation of 
org.apache.soap.util.net.HTTPUtils that works for me
as a "plugin replacement".

Do you think that is a good idea?

Thank you,
Achim
/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "SOAP" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact [EMAIL PROTECTED]
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 2000, International
 * Business Machines, Inc., http://www.apache.org.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */



import java.net.*;
import java.io.*;
import java.util.*;

import org.apache.soap.Constants;
import org.apache.soap.SOAPException;
import org.apache.soap.transport.TransportMessage;
import org.apache.soap.rpc.SOAPContext;
import org.apache.soap.util.mime.ByteArrayDataSource;
import javax.mail.MessagingException;

/**
 * plugin replacemet of org.apache.soap.util.net.HTTPUtils
 * that supports usage of java.net.Authenticator
 * @author Achim Grolms [EMAIL PROTECTED]
 
 */
public class AIDAHTTPUtils {

  public  static final int    DEFAULT_OUTPUT_BUFFER_SIZE = 512;


  /**
   * POST something to the given URL. The headers are put in as
   * HTTP headers, the content length is calculated and the content
   * byte array is sent as the POST content.
   *
   * @param url the url to post to
   * @param request the message
   * @param timeout the amount of time, in ms, to block on reading data
   * @param httpProxyHost the HTTP proxy host or null if no proxy
   * @param httpProxyPort the HTTP proxy port, if the proxy host is not null
   * @return the response message
   */
  public static TransportMessage post(URL url, TransportMessage request,
                                      int timeout,
                                      String httpProxyHost, int httpProxyPort)
      throws IllegalArgumentException, IOException, SOAPException {
    return post(url,
                request,
                timeout,
                httpProxyHost,
                httpProxyPort,
                DEFAULT_OUTPUT_BUFFER_SIZE,
                null);
  }

  /**
   * POST something to the given URL. The headers are put in as
   * HTTP headers, the content length is calculated and the content
   * byte array is sent as the POST content.
   *
   * @param url the url to post to
   * @param request the message
   * @param timeout the amount of time, in ms, to block on reading data
   * @param httpProxyHost the HTTP proxy host or null if no proxy
   * @param httpProxyPort the HTTP proxy port, if the proxy host is not null
   * @param outputBufferSize the size of the output buffer on the HTTP stream
   * @return the response message
   */
  public static TransportMessage post(URL url, TransportMessage request,
                                      int timeout,
                                      String httpProxyHost, int httpProxyPort,
                                      int outputBufferSize)
      throws IllegalArgumentException, IOException, SOAPException {
    return post(url,
                request,
                timeout,
                httpProxyHost,
                httpProxyPort,
                outputBufferSize,
                null);
  }

  /**
   * POST something to the given URL. The headers are put in as
   * HTTP headers, the content length is calculated and the content
   * byte array is sent as the POST content.
   *
   * @param url the url to post to
   * @param request the message
   * @param timeout the amount of time, in ms, to block on reading data
   * @param httpProxyHost the HTTP proxy host or null if no proxy
   * @param httpProxyPort the HTTP proxy port, if the proxy host is not null
   * @param outputBufferSize the size of the output buffer on the HTTP stream
   * @param tcpNoDelay the tcpNoDelay setting for the socket
   * @return the response message
   */
  public static TransportMessage post(URL url, TransportMessage request,
                                      int timeout,
                                      String httpProxyHost, int httpProxyPort,
                                      int outputBufferSize,
                                      Boolean tcpNoDelay)
      throws IllegalArgumentException, IOException, SOAPException {
      
      TransportMessage response = null;
      DataOutputStream bOutStream = null;
      BufferedInputStream bInStream = null;
      HttpURLConnection uc = null;
      //----------------------------------------------------------
      try { 
          uc = (HttpURLConnection)buildurlconnection( url, request );
          bOutStream = new DataOutputStream( uc.getOutputStream() );
          request.writeTo(bOutStream);
          bOutStream.flush();
          bInStream= new BufferedInputStream( uc.getInputStream() );
      
          ByteArrayDataSource ds = new ByteArrayDataSource(bInStream,
                              Constants.HEADERVAL_DEFAULT_CHARSET);
          byte[] bytes = ds.toByteArray();
          InputStream is = ds.getInputStream();
      
          response = constructResponseObject( is, uc);
          bOutStream.close();
          bInStream.close();      
      }
      catch  (IOException ex) {
      
        try {
               BufferedReader errorinput = new BufferedReader(
                                              new InputStreamReader( uc.getErrorStream()
                                        ) );
               String line = "";
               String errortext = new String();
               while(( line = errorinput.readLine()) != null )
                       errortext = errortext +line + "\n" ;
               errorinput.close();
               throw new IOException( errortext );

        } catch  (IOException ex2) {
               throw new IOException( ex.getMessage() + "\n\n" + ex2.getMessage());
        }
      
      }   
      return response;      
  }
  /* --------------------------------------------------------------------- */
  protected static TransportMessage constructResponseObject( InputStream   inputstream,
                                                             URLConnection urlconnection)
                   throws java.io.IOException, 
                          org.apache.soap.SOAPException {
          
      SOAPContext ctx = null;
      TransportMessage response = null;   
      try {
          ctx = new SOAPContext();  // Create response SOAPContext.
          // Read content.
          response = new TransportMessage(inputstream, 
                                          urlconnection.getContentLength(),
                                          urlconnection.getContentType(), 
                                          ctx, 
                                          createreponseheader( urlconnection  ));
          // Extract envelope and SOAPContext
          response.read();
      } catch (MessagingException me) {
         
          throw new IllegalArgumentException("Error parsing response: " + me);
      }      
      return response;
  }
  /* --------------------------------------------------------------------- */
  protected static Hashtable createreponseheader(URLConnection urlconnection) {
      Hashtable respHeaders = new Hashtable();
      int fieldi = 2;  // ueberlesen von HTTP und Zeit
      while( true ) {
         String headervalue = urlconnection.getHeaderField( fieldi );
         String headerkey = urlconnection.getHeaderFieldKey(fieldi);
         if (headervalue == null ) {
            break;
         }
         respHeaders.put(headerkey, headervalue);
         fieldi++;
      }
      return respHeaders;
  }
  /* --------------------------------------------------------------------- */
  protected static URLConnection buildurlconnection( URL url, 
                                                     TransportMessage request )
                   throws java.io.IOException {
      URLConnection uc = url.openConnection();
      
      uc.setAllowUserInteraction( true );
      uc.setDoOutput( true );
      uc.setDoInput(true);
      uc.setUseCaches( false );
      
      uc.setRequestProperty("Host", url.getHost() + ":" + Integer.toString(url.getPort()));
      uc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
      uc.setRequestProperty("Content-Length", 
                             Integer.toString( request.getContentLength() ) );
      uc.setRequestProperty("SOAPAction",  "\"\"");
      uc.setRequestProperty("Accept-Encoding", "utf-8");
      uc.setRequestProperty("Accept-Charset", "utf-8");
      uc.setRequestProperty("Accept", "*/*");
      uc.setRequestProperty("User-Agent", getUserAgentName() );
      return uc;
  }
  /* --------------------------------------------------------------------- */
  protected static String getUserAgentName() {
     return("Java SOAP Client derived from org.apache.soap.util.net.HTTPUtils by [EMAIL PROTECTED]");
  }
  /* --------------------------------------------------------------------- */
}

Reply via email to