轉:使用基本認證從WebServer獲取資料

herosoft發表於2008-09-22

轉:使用基本認證從WebServer獲取資料

[@more@]
/**
 * This class sends request to the specified URL and reads the response.
 *
 * Uses basic authentication to authenticate with the Server and writes the
 * request to the specified URL. Response can be either be read as an Object or

 * as BinaryStream or as AsciiStream.
 *
 */
public class ServletUtils {
 
  private static final int BUFFSIZE = 4 * 1024; // buffer size - 4K
 
  /**
   * Default Constructor.
   */
  public ServletUtils()  {
 
  }
 
  /**
   * This method establishes connection to the specified server and authenticates
   * using the specified username and password.
   *
   * @param     servletUrl URL of the server to send request
   * @param     username user name to be used for authentication with server
   * @param     password password to be user for authentication with server
   *
   * @return URLConnection instance of connection to the specified server
   */
 
  public HttpURLConnection getServerConnection( String server, String username,
                                            String password )
      throws Exception {
 
    HttpURLConnection urlConn = null;
 
    URL url = new URL(server);
 
    // Build the string to be used for Basic Authentication :
    String userPassword =  username + ":" + password;
 
    // Base64 encode the authentication string
    String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes());
 
 
    //URLConnection
    urlConn = (HttpURLConnection) url.openConnection();
 
    // Enable writing to server ( to write request )
    urlConn.setDoOutput(true);
 
    // Enable reading from server ( to read response )
    urlConn.setDoInput(true);
 
    // Disable cache
    urlConn.setUseCaches(false);
    urlConn.setDefaultUseCaches(false);
 
 
    // Set Basic Authentication parameters
    urlConn.setRequestProperty ("Authorization", "Basic " + encoding);
 
    return urlConn;
  }
 
  /**
   * This method sends the specified request to the given url and returns the
   * response as an Object. If the returned Object is an instance of
   * CMSAccessException, throws it.
   *
   * @param     req  HttpServletRequest that has to be sent to the server
   * @param     servletUrl URL of the server to send request
   * @param     username user name to be used for authentication with server
   * @param     password password to be user for authentication with server

   *
   * @return  Response from the server
   *
   * @exception CMSAccessException if server could not handle the request
   */
  public Object sendRequest(HttpServletRequest req, String servletUrl,
                            String username, String password)
      throws CMSAccessException {
 
    // Response from server
    Object responseObj = null;
 
    HttpURLConnection urlConn = null;
 
    try {
 
 
      String res = "Nothing was returned";
 
System.out.println( "*************"  );
System.out.println( "Username : " + username );
System.out.println( "Password : " + password );
 
      urlConn = this.getServerConnection(servletUrl, username, password);
 
System.out.println( "ServletURL : " + servletUrl );
System.out.println( "*************"  );
 
      String contenttype = req.getHeader( "Content-Type" );
 
      // Set Content Type
      if (contenttype != null) {
        urlConn.setRequestProperty("Content-Type", contenttype);
      } else {
 
        urlConn.setRequestProperty("Content-Type", "text/plain");
      }
 
      // Get output stream of server to send the request
      BufferedOutputStream connOut = new BufferedOutputStream(urlConn.getOutputStream());
 
System.out.println( "bef urlconn"  );
      // Establish connection to server
      urlConn.connect();
 
      byte[] buffer = new byte[ BUFFSIZE ];
      int len = 0;
 
System.out.println( "get input stream"  );
      // Get the input stream for request
      ServletInputStream in = req.getInputStream();
 
System.out.println( "read and write"  );
 
      // Write request
      while ((len = in.read(buffer,0,buffer.length )) >-1) {
        connOut.write(buffer,0,len);
      }
System.out.println( "done writing ..."  );
 
      // Close
      connOut.flush();
      connOut.close();
      in.close();
 
      // Completed sending request, now read response
 
System.out.println( "output stream"  );
      // Read the object send by server
      ObjectInputStream inputFromServlet = new ObjectInputStream(urlConn.getInputStream());
System.out.println( "bef readobj"  );
      responseObj = inputFromServlet.readObject();
System.out.println( "readobj done..."  );
 
      inputFromServlet.close();
 
    } catch (Exception ex) {
 
      throw new CMSAccessException ( "Error sending request  : " +
                                     ex.toString() );
 
    } finally {
 
      // Disconnect
      if( urlConn != null ) {
        urlConn.disconnect();
        urlConn = null;
      }
 
    }
 
    // Check if response is an error message
    if ( responseObj instanceof CMSAccessException ) {
      throw (CMSAccessException)responseObj;
 
    }
 
    return responseObj;
 
  }
 
  /**
   * This method sends the specified request to XDB server and returns the
   * response as a String. The request would be for a particular file, XDB
   * server responds with the contents of the file which is returned by this method.
   *
   * Uses the Authenticator class to authenticate with XDB server.
   *
   * @param     req  HttpServletRequest that has to be sent to the server
   * @param     servletUrl URL of the server to send request
   * @param     username user name to be used for authentication with server
   * @param     password password to be user for authentication with server
   *
   * @return  File contents of the specified file
   *
   * @exception CMSAccessException if server could not handle the request

   */
  public String  sendXDBServletRequest(HttpServletRequest req, String servletUrl,
                                 String username, String password)
      throws CMSAccessException {
 
    HttpURLConnection urlConn = null;
    StringBuffer      sb      = new StringBuffer();
    try {
 
      URL url = new URL(servletUrl);
 
      // Use Authenticator to provide authentication info to XDB servlet
      Authenticator.setDefault(new AuthImpl(username,password));
 
      //URLConnection
      urlConn = (HttpURLConnection) url.openConnection();
 
      // Enable writing to server ( to write request )
      urlConn.setDoOutput(true);
 
      // Enable reading from server ( to read response )
      urlConn.setDoInput(true);
 
 
      // Get output stream of server to send the request
      BufferedOutputStream connOut = new BufferedOutputStream(urlConn.getOutputStream());
 
      urlConn.connect();
 
      byte[] buffer = new byte[ BUFFSIZE ];
      int len = 0;
 
      // Get the input stream for request
      ServletInputStream in = req.getInputStream();
 
      // Write request
      while ((len = in.read(buffer,0,buffer.length )) >-1) {
        connOut.write(buffer,0,len);
      }
 
      // Close
      connOut.flush();
      connOut.close();
      in.close();
 
      // Completed sending request, now read response
 
 
      // Get handle to  server response
      InputStream content = (InputStream) url.getContent();
      BufferedReader servletin = new BufferedReader(new InputStreamReader(content));
 
      String line = null;
 
      // Read contents from XDB server
      while ((line = servletin.readLine()) != null) {
        sb.append(line);
        sb.append('n');
      }
      servletin.close();
 
    } catch (Exception ex) {
 
      throw new CMSAccessException ( "Exception at sendXDBServletRequest method : " +
                                     ex.toString() );
    } finally {
 
      // Disconnect
      if( urlConn != null ) {
        urlConn.disconnect();
        urlConn = null;
 
      }
    }
 
    return sb.toString();
 
  }
 
 
  /**
   * This method sends the specified request using GET method to server and
   * writes the response to the specified HttpServletResponse.
   *
   * @param     res  HttpServletResponse to which server response has to be written
   * @param     servletUrl URL of the server to send request
   * @param     username user name to be used for authentication with server
   * @param     password password to be user for authentication with server
   *
   * @exception CMSAccessException if server could not handle the request
   */
  public void sendXDBServletRequest(HttpServletResponse  res, String servletUrl,
                                 String username, String password)
       throws CMSAccessException   {
 
    HttpURLConnection urlConn = null;
    BufferedInputStream in    = null;
 
    BufferedOutputStream bout = null;
 
    try {
 
      // Authenticate with server and get connection
      urlConn = this.getServerConnection(servletUrl, username, password);
 
      byte[] buffer = new byte[ BUFFSIZE ];
      int len = 0;
 
      // Get response from server
      in = new BufferedInputStream( urlConn.getInputStream( ) );
 
      // Set response content type
      res.setContentType( urlConn.getContentType() );
 
      // Get handle to response output stream
      bout = new BufferedOutputStream( res.getOutputStream( ) );
 
      // Reads from server and write to response
      while( ( len = in.read(buffer,0,buffer.length) ) > -1 ) {
        bout.write(buffer, 0, len );
      }
 
    } catch (IOException ioEx) {
 
 
      System.out.println( " IO Error occured while communicating with server : " +
                         ioEx.toString( ) );
 
    } catch (Exception ex) {
 
      throw new CMSAccessException ( "Error communicating with server : " +
                                     ex.toString() );
    } finally {
 
      try {
        if( in != null ) in.close();
        if( bout != null ) bout.close();
      } catch(IOException ioEx)  {
        System.out.println(" Error closing streams : " + ioEx.toString());
      }
      // Disconnect
      if( urlConn != null ) {
        urlConn.disconnect();
        urlConn = null;
      }
    }
 
  }
 
  // Inner class
 
  /**

   * This inner class is invoked whenever a server requires Authentication.
   */
  class AuthImpl extends Authenticator {
 
    private String user=null;
    private String pwd = null;
 
    /**
     * Constructs a new Authenticator object with the specified username and
     * password.
     *
     * @param user username for authentication
     * @param pass password for authentication
     */
    public AuthImpl(String user,String pass) {
      this.user = user;
      this.pwd = pass;
    }
 
    /**
     * This method is invoked if the server requests authentication information.
     *
     * @return user credentials for authentication
     */
    protected PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(user, pwd.toCharArray());
    }
 } // End of Inner class
 
 
}
 Trackback:
http://anotherbug.blog.chinajavaworld.com/entry/4060/15

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/220284/viewspace-1010912/,如需轉載,請註明出處,否則將追究法律責任。

相關文章