Here is example code for HTTPS Tunneling through proxy(400 Lines of code

Here is the source for Https Tunneling that I have gotten working. It is based on Pua Yeow Cheong's JavaWorld Tip 111. Thanks to David Lord for providing the final breakthrough that I needed.
I have posted it here for anyone who wishes to use it. If you find any bugs, or write any improvements, please tack them onto the end of this thread.
I have been trying to tackle this problem for quite some time, so I hope this helps a few of you out there.
Lots of Luck,
nightmask.
<----- Begin Copy and Paste -------->
import java.net.*;
import java.io.*;
import java.security.*;
import sun.misc.BASE64Encoder;
import javax.net.*;
import javax.net.ssl.*;
*  This example is based on JavaWorld Tip 111. Thanks to Pua Yeow Cheong for writing it.
*  It tunnels through a proxy using the Https protocol.
*  Thanks go to David Lord in the java forums for figuring out the main problem with Tip 111
*  PLEASE NOTE: You need to have the JSSE 1.0.2 jars installed for this to work
*  Downloads contents of a URL, using Proxy Tunneling and Basic Authentication
public class URLReader {
     *  The main program for the URLReader class
    public static void main(String[] args) throws Exception {
        //set up strings for use in app. Change these to your own settings
        String proxyPassword = "password";
        String proxyUsername = "username";
        String proxyHost = "myproxy.com";
        String proxyPort = "3128";
        String connectionURL = "https://www.verisign.com";
        //set up system properties to indicate we are using a proxy
        System.setProperty("https.proxyHost", proxyHost);
        System.setProperty("https.proxyPort", proxyPort);
        System.setProperty("proxyHost", proxyHost);
        System.setProperty("proxyPort", proxyPort);
        System.setProperty("proxySet", "true");
        System.setProperty("http.proxyHost", proxyHost);
        System.setProperty("http.proxyPort", proxyPort);
        System.setProperty("http.proxySet", "true");
        //set up handler for jsse
        System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
        java.security.Provider prov = new com.sun.net.ssl.internal.ssl.Provider();
        Security.addProvider(prov);
        //create the connection
        URL myURL = new URL(connectionURL);
        URLConnection myConnection = myURL.openConnection();
        if (myConnection instanceof com.sun.net.ssl.HttpsURLConnection) {
            ((com.sun.net.ssl.HttpsURLConnection) myConnection).setSSLSocketFactory(new SSLTunnelSocketFactory(System.getProperty("proxyHost"), System.getProperty("proxyPort")));
        myConnection.setDoInput(true);
        myConnection.setDoOutput(true);
        BufferedReader in;
        try {
            System.err.println("opening Input stream1");
            in = new BufferedReader(
                    new InputStreamReader(
                    myConnection.getInputStream()));
            String inputLine;
            System.err.println("Input stream is Open1");
            while ((inputLine = in.readLine()) != null) {
                System.err.println(inputLine);
            in.close();
            System.err.println("Input stream is Closed1");
        } catch (Exception e) {
            e.printStackTrace(System.err);
            String tmp = e.getMessage().toLowerCase().trim();
            System.err.println("tmp *" + tmp + "*");
            if (tmp.indexOf("http") > -1) {
                //http error message to be parsed
                tmp = tmp.substring(tmp.indexOf("http")).trim();
                System.err.println("tmp *" + tmp + "*");
                tmp = tmp.substring(8).trim();
                System.err.println("tmp *" + tmp + "*");
                if (tmp.startsWith("407")) {
                    //proxy authentication required
                    myURL = new URL(connectionURL);
                    myConnection = myURL.openConnection();
                    if (myConnection instanceof com.sun.net.ssl.HttpsURLConnection) {
                        ((com.sun.net.ssl.HttpsURLConnection) myConnection).setSSLSocketFactory(new SSLTunnelSocketFactory(System.getProperty("proxyHost"), System.getProperty("proxyPort"), proxyUsername, proxyPassword));
                    myConnection.setDoInput(true);
                    myConnection.setDoOutput(true);
                    try {
                        System.err.println("opening Input stream 2");
                        in = new BufferedReader(
                                new InputStreamReader(
                                myConnection.getInputStream()));
                        String inputLine;
                        System.err.println("Input stream is Open 2");
                        while ((inputLine = in.readLine()) != null) {
                            System.out.println(inputLine);
                        in.close();
                        System.err.println("Input stream is closed 2");
                    } catch (Exception ex) {
                        System.err.println(ex.getMessage());
                        ex.printStackTrace(System.err);
*  SSLSocket used to tunnel through a proxy
class SSLTunnelSocketFactory extends SSLSocketFactory {
    private String tunnelHost;
    private int tunnelPort;
    private SSLSocketFactory dfactory;
    private String tunnelPassword;
    private String tunnelUserName;
    private boolean socketConnected = false;
    private int falsecount = 0;
     *  Constructor for the SSLTunnelSocketFactory object
     *@param  proxyHost  The url of the proxy host
     *@param  proxyPort  the port of the proxy
    public SSLTunnelSocketFactory(String proxyHost, String proxyPort) {
        System.err.println("creating Socket Factory");
        tunnelHost = proxyHost;
        tunnelPort = Integer.parseInt(proxyPort);
        dfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
     *  Constructor for the SSLTunnelSocketFactory object
     *@param  proxyHost      The url of the proxy host
     *@param  proxyPort      the port of the proxy
     *@param  proxyUserName  username for authenticating with the proxy
     *@param  proxyPassword  password for authenticating with the proxy
    public SSLTunnelSocketFactory(String proxyHost, String proxyPort, String proxyUserName, String proxyPassword) {
        System.err.println("creating Socket Factory with password/username");
        tunnelHost = proxyHost;
        tunnelPort = Integer.parseInt(proxyPort);
        tunnelUserName = proxyUserName;
        tunnelPassword = proxyPassword;
        dfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
     *  Sets the proxyUserName attribute of the SSLTunnelSocketFactory object
     *@param  proxyUserName  The new proxyUserName value
    public void setProxyUserName(String proxyUserName) {
        tunnelUserName = proxyUserName;
     *  Sets the proxyPassword attribute of the SSLTunnelSocketFactory object
     *@param  proxyPassword  The new proxyPassword value
    public void setProxyPassword(String proxyPassword) {
        tunnelPassword = proxyPassword;
     *  Gets the supportedCipherSuites attribute of the SSLTunnelSocketFactory
     *  object
     *@return    The supportedCipherSuites value
    public String[] getSupportedCipherSuites() {
        return dfactory.getSupportedCipherSuites();
     *  Gets the defaultCipherSuites attribute of the SSLTunnelSocketFactory
     *  object
     *@return    The defaultCipherSuites value
    public String[] getDefaultCipherSuites() {
        return dfactory.getDefaultCipherSuites();
     *  Gets the socketConnected attribute of the SSLTunnelSocketFactory object
     *@return    The socketConnected value
    public synchronized boolean getSocketConnected() {
        return socketConnected;
     *  Creates a new SSL Tunneled Socket
     *@param  s                         Ignored
     *@param  host                      destination host
     *@param  port                      destination port
     *@param  autoClose                 wether to close the socket automaticly
     *@return                           proxy tunneled socket
     *@exception  IOException           raised by an IO error
     *@exception  UnknownHostException  raised when the host is unknown
    public Socket createSocket(Socket s, String host, int port, boolean autoClose)
             throws IOException, UnknownHostException {
        Socket tunnel = new Socket(tunnelHost, tunnelPort);
        doTunnelHandshake(tunnel, host, port);
        SSLSocket result = (SSLSocket) dfactory.createSocket(tunnel, host, port, autoClose);
        result.addHandshakeCompletedListener(
            new HandshakeCompletedListener() {
                public void handshakeCompleted(HandshakeCompletedEvent event) {
                    System.out.println("Handshake Finished!");
                    System.out.println("\t CipherSuite :" + event.getCipherSuite());
                    System.out.println("\t SessionId: " + event.getSession());
                    System.out.println("\t PeerHost: " + event.getSession().getPeerHost());
                    setSocketConnected(true);
        // thanks to David Lord in the java forums for figuring out this line is the problem
        // result.startHandshake(); //this line is the bug which stops Tip111 from working correctly
        return result;
     *  Creates a new SSL Tunneled Socket
     *@param  host                      destination host
     *@param  port                      destination port
     *@return                           tunneled SSL Socket
     *@exception  IOException           raised by IO error
     *@exception  UnknownHostException  raised when the host is unknown
    public Socket createSocket(String host, int port)
             throws IOException, UnknownHostException {
        return createSocket(null, host, port, true);
     *  Creates a new SSL Tunneled Socket
     *@param  host                      Destination Host
     *@param  port                      Destination Port
     *@param  clientHost                Ignored
     *@param  clientPort                Ignored
     *@return                           SSL Tunneled Socket
     *@exception  IOException           Raised when IO error occurs
     *@exception  UnknownHostException  Raised when the destination host is
     *      unknown
    public Socket createSocket(String host, int port, InetAddress clientHost,
            int clientPort)
             throws IOException, UnknownHostException {
        return createSocket(null, host, port, true);
     *  Creates a new SSL Tunneled Socket
     *@param  host             destination host
     *@param  port             destination port
     *@return                  tunneled SSL Socket
     *@exception  IOException  raised when IO error occurs
    public Socket createSocket(InetAddress host, int port)
             throws IOException {
        return createSocket(null, host.getHostName(), port, true);
     *  Creates a new SSL Tunneled Socket
     *@param  address          destination host
     *@param  port             destination port
     *@param  clientAddress    ignored
     *@param  clientPort       ignored
     *@return                  tunneled SSL Socket
     *@exception  IOException  raised when IO exception occurs
    public Socket createSocket(InetAddress address, int port,
            InetAddress clientAddress, int clientPort)
             throws IOException {
        return createSocket(null, address.getHostName(), port, true);
     *  Sets the socketConnected attribute of the SSLTunnelSocketFactory object
     *@param  b  The new socketConnected value
    private synchronized void setSocketConnected(boolean b) {
        socketConnected = b;
     *  Description of the Method
     *@param  tunnel           tunnel socket
     *@param  host             destination host
     *@param  port             destination port
     *@exception  IOException  raised when an IO error occurs
    private void doTunnelHandshake(Socket tunnel, String host, int port) throws IOException {
        OutputStream out = tunnel.getOutputStream();
        //generate connection string
        String msg = "CONNECT " + host + ":" + port + " HTTP/1.0\n"
                 + "User-Agent: "
                 + sun.net.www.protocol.http.HttpURLConnection.userAgent;
        if (tunnelUserName != null && tunnelPassword != null) {
            //add basic authentication header for the proxy
            sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
            String encodedPassword = enc.encode((tunnelUserName + ":" + tunnelPassword).getBytes());
            msg = msg + "\nProxy-Authorization: Basic " + encodedPassword;
        msg = msg + "\nContent-Length: 0";
        msg = msg + "\nPragma: no-cache";
        msg = msg + "\r\n\r\n";
        System.err.println(msg);
        byte b[];
        try {
            //we really do want ASCII7 as the http protocol doesnt change with locale
            b = msg.getBytes("ASCII7");
        } catch (UnsupportedEncodingException ignored) {
            //If ASCII7 isn't there, something is seriously wrong!
            b = msg.getBytes();
        out.write(b);
        out.flush();
        byte reply[] = new byte[200];
        int replyLen = 0;
        int newlinesSeen = 0;
        boolean headerDone = false;
        InputStream in = tunnel.getInputStream();
        boolean error = false;
        while (newlinesSeen < 2) {
            int i = in.read();
            if (i < 0) {
                throw new IOException("Unexpected EOF from Proxy");
            if (i == '\n') {
                headerDone = true;
                ++newlinesSeen;
            } else
                    if (i != '\r') {
                newlinesSeen = 0;
                if (!headerDone && replyLen < reply.length) {
                    reply[replyLen++] = (byte) i;
        //convert byte array to string
        String replyStr;
        try {
            replyStr = new String(reply, 0, replyLen, "ASCII7");
        } catch (UnsupportedEncodingException ignored) {
            replyStr = new String(reply, 0, replyLen);
        //we check for connection established because our proxy returns http/1.1 instead of 1.0
        if (replyStr.toLowerCase().indexOf("200 connection established") == -1) {
            System.err.println(replyStr);
            throw new IOException("Unable to tunnel through " + tunnelHost + ":" + tunnelPort + ". Proxy returns\"" + replyStr + "\"");
        //tunneling hanshake was successful
}<----- End Copy and Paste -------->

BTW, if you are using an implementation in which
the http/https implementation recognises
the java.net.Authenticator properly, you can use
that framework to do basic/digest authentication.
I think Sun's JDK 1.4 supports both basic
and digest for both proxies and the actual end
site you connect via http/https, but I haven't
tested it to be sure. I know it works
with http/basic at the end host.
Today's Ob hack:
import java.net.*;
import java.io.*;
class MyAuth extends Authenticator {
    protected PasswordAuthentication getPasswordAuthentication() {
        System.out.println("The realm '" + getRequestingPrompt() +
            "' at '" + getRequestingHost() + ":" + getRequestingPort() +
            "'\n" + "using " + getRequestingProtocol() + " is requesting " +
            getRequestingScheme().toUpperCase() + " authentication.");
        System.out.println("");
        System.out.println("What should we send them?  Let's send them ...");
        System.out.println("");
        return new PasswordAuthentication("username", "password".toCharArray());    }  
public class MyURL {
    public static void main(String[] args) throws Exception {
        // set to the authenticator you want to use.
        Authenticator.setDefault(new myAuth());
        URL url =
            new URL("http://www.some.com/something_protected/index.htm");
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                url.openStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            System.out.println(inputLine);
        in.close();

Similar Messages

  • Dont think RMi is HTTP tunneling through proxy firewall

    Hi Guys,
    Does anyone know how to monitor if RMI is using the option toHTTP tunnel through a proxy ???
    Many of clients sit behind firewalls/proxies that enable HTTP only. I thought RMI would, as a default, use HTTP tunneling POST, RESPONSe methods to get through, but it does not.
    Would that case be insted of using Naming.lokup("RMIServer"); that i should use
    Registry reg = LocateRegistry.getResgistry(serverAddress, serverPort);
    reg.lookup("RMIServer");
    Any help would be greatly appreciated.

    RMI doesn't have an option like that. Sockets do, and you get it for any socket including RMI by setting socksProxyHost and socksProxyPort.
    The RMI HTTP tunnelling thing happens when there is an HTTP server at the server side. which redirects the request to an RMI server via rmi-cgi.cgi or the RMI servlet. It's automatic, as a fallback, and you can enforce its use via a system property which you can find in the Javadoc Guide to Features/Remote Method Invocation/Useful java.rmi system properties.

  • HTTP-Tunneling through Apache Plug-in

    Hello,
    has anybody experience with HTTP-Tunneling of requests to a WLS
    4.5.1SP13 through an Apache-Webserver?
    I'm not able to configure the apache plug-in from weblogic to act as a
    reverse proxy for requests coming from a
    Java Client Application.
    Any Hints available?
    Remo

    "Jong Lee" <[email protected]> wrote in message
    news:3a4a9efa$[email protected]..
    >
    Remo Schnidrig <[email protected]> wrote:
    Hello Jong,
    HTTP tunneling will append ".tun" to your request.
    For apache, you can use "MatchExpression" to proxy the mime type.
    i.e: add the following line to your httpd.conf
    MatchExpression *.tunThat is functioning. Thank you very much.
    Another question:
    What about HTTPS-Tunneling through an Apache-Server?
    How can I get everything through?
    Thank you
    Remo
    We don't support https from the bridge to the server yet.
    JongWhat about using HTTPS-Tunneling between our Java client and the WLS
    Stronghold plug-in and HTTP-Tunneling between the plug-in and the WLS?
    If this is possible, how do I have to setup the stronghold?
    Remo

  • Re: (forte-users) HTTP request through proxy server

    Daniel -
    No, it does not. ;)
    How do you say to HTTPRequest to go through proxy?
    Thanks,
    Taras
    Daniel Nguyen wrote:
    >
    Hi,
    It works very well. I have experienced this model for a distant Forte client
    calling a Forte Server service Object for instance without any environment
    and without TCP access (passing through firewall for instance).
    It has also worked very well to make an injectot to improve Web Enterprise
    and IIS using the SendRequest from HTTPAccess.
    Hope this helps,
    Daniel Nguyen
    Freelance Forte Consultant
    http://perso.club-internet.fr/dnguyen/
    Taras Katkov a &eacute;crit:
    HTTP request through proxy server using forte HTTP library?
    Any experience?
    Thanks,
    Taras
    For the archives, go to: http://lists.xpedior.com/forte-users and use
    the login: forte and the password: archive. To unsubscribe, send in a new
    email the word: 'Unsubscribe' to: forte-users-requestlists.xpedior.com--
    For the archives, go to: http://lists.xpedior.com/forte-users and use
    the login: forte and the password: archive. To unsubscribe, send in a new
    email the word: 'Unsubscribe' to: forte-users-requestlists.xpedior.com

    You can also use the HTTP-DC project.... You don't
    need Web Enterprise for this. From what I can tell,
    this is available in L.x on....
    There is api documentation in M.2 (with scant
    examples.)
    There's a special process to put the project in your
    repository (it isn't installed in the repository in
    the standard install,) the documentation in M.2
    (probably in M.0 too, AFAIK) that tells you how to do
    this (look for HTTP-DC in the online help.)
    I haven't done much with it yet, I've just installed
    it. If anybody out there has examples, that'd be
    great. I'll try to contribute more the moment I get a
    chance to explore it....
    Christopher Fury
    BellSouth Communications Systems
    --- Daniel Nguyen <dnguyenclub-internet.fr> wrote:
    Hi,
    If you have Web Enterprise, you can user
    HttpAccess.SendRequest().
    Hope this helps,
    Daniel Nguyen
    Freelance Forte Consultant
    Amin, Kamran a &eacute;crit:
    Is there any way to make a HTTP request from TOOLto another HTTP Service?
    thanks in advance.
    For the archives, go to:
    http://lists.xpedior.com/forte-users and use
    the login: forte and the password: archive. Tounsubscribe, send in a new
    email the word: 'Unsubscribe' to:forte-users-requestlists.xpedior.com
    For the archives, go to:
    http://lists.xpedior.com/forte-users and use
    the login: forte and the password: archive. To
    unsubscribe, send in a new
    email the word: 'Unsubscribe' to:
    forte-users-requestlists.xpedior.com
    Kick off your party with Yahoo! Invites.
    http://invites.yahoo.com/

  • For http tunnel

    hi dear to all
    i am new to http tunneling.
    i want to know how should i confignure the SSL between the webserver to database server. because i want to send/receiver the data from database. i want to know how should i configure the ssl in sever? is there any options for that? what r the softwares required for that? if it is not possible manually if write the code for SSL ; is it possible to keep between server and database. if u have the code please provide me.
    thank u
    regards
    krishna

    Hi krishna,
    Why do you need to tunnel from App Server to Database?
    Dont you use JDBC???
    If not, are you using some kind of protocol to access data from Database? I know people use SOAP Messages in Web Services to access Database.
    Please let us know what is your real requirement for us to understand your architecture more and give possible options.
    Thanks and regards,
    Pazhanikanthan. P

  • Settings to be done for Apache/Tomcat for HTTP tunneling?

    What are the settings that i need to do for Apache/Tomcat to run http tunneling over rmi.
    Thanks in advance.

    Hi thanks for reply.
    i am trying to run the application which comes from sun doc(rmiservlethandler).
    in one article i have found that we have to set up the Apache/Tomcat in order to rewrite the rmi-cgi call to the servlet.
    i am not able to make run rmiservlethandler app. any tips for this app to run on Apache/Tomcat.

  • Example-WSDL for http-POST binding

    Hi all,
    i'm looking for an example-WSDL of a http-POST binded service. I was searching in the ~\OraBPELPM_1\integration\orabpel\samples\tutorials\702.Bindings\HTTPBinding directory, but its the example is of a http-get binded service.
    I need to know, how the message-definitions for the input have to look like (in the message-section and in the operation-section) when using an XML-input message.
    thanks in advance
    Albrecht

    Gee! i didn't know there are some more samples! :o)
    Thanks Clemens, i will test it.

  • HTTPS Recording through proxy

    Hi all
    I'm trying to record through a proxy using OpenScript 9.0.1. When the site is an HTTP site, all is fine and I'm asked for my proxy password and then passed on to the site. OpenScript records as expected. But when the site is HTTPS, I don't get the proxy authorisation box and eventually the following is returned. Content-length: 0 Connection: Keep-Alive
    Has anyone got experience of recording HTTPS through a proxy. I'm trying to work out if it's OpenScript, the proxy or some network security issue.
    I've tried both to use the IE settings or manually specify proxy settings in OpenScript.
    Another interesting issue is that the 'ignore' list in IE does not seem to be used by OpenScript and there is no way in the OpenScript prefs to set a proxy ignore list?
    many thanks
    Wilbo.

    nobody knows?How about you... do you know the answer? Then tell us. :p

  • NAT slooows over time (2 days) for http users. Proxy users OK.

    We recently applied NW6 sp4 to a stable BM 3.7 server. Now internal
    dynamic NATed http users experience a progressive slow down over about 2
    days at which time browsing is functional but not usable. Proxy users
    still get screamingly fast performance.

    > How much traffic is going out via dynamic NAT?
    >
    > Have you tried using non-stateful http filter exceptions?
    >
    > BM37FP4A?
    >
    > Backrev NAT?
    >
    > Craig Johnson
    > Novell Support Connection SysOp
    > *** For a current patch list, tips, handy files and books on
    > BorderManager, go to http://www.craigjconsulting.com ***
    >
    Problem appears to be resolved. I applied BM37FP4A and after 3 days NATed
    HTTP connections are normal. Proxy performance is still very fast. I had
    previously reapplied bm37sp3 which did not solve the problem.
    FYI: About 1/2 of our 800 or so connections use dynamic NAT. We plan on
    switching all users to proxy this week. Thanks Craig.

  • Use of servlet http tunneling for client server communication

    Hello I am having a problem connecting a simple client applet to a server application. I can connect the two directly using sockets. However, when I try to connect the two via a servlet the input stream cannot be accessed. The application is purely for demonstration. Here is some of the source code
    A servlet for http tunneling
    import java.io.*;
    import java.net.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class SocketServlet extends HttpServlet
         ServletInputStream servletinput;
         ServletOutputStream servletoutput;
         Socket socket;
         DataOutputStream dataoutput;
         DataInputStream datainput;     
         public SocketServlet()
    public void init(ServletConfig servletconfig) throws ServletException
    super.init(servletconfig);
    log("Socket servlet initialized.");
         public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
    try
    servletinput = request.getInputStream();
    socket = new Socket( InetAddress.getByName( "127.0.0.1" ), 5000 );
    dataoutput = new DataOutputStream( socket.getOutputStream() );
    try
                        byte[] inbytes = new byte[1024];
                        servletinput.read( inbytes );
                        String inmessage = new String( inbytes );                    
                        dataoutput.writeBytes( inmessage );
    catch(IOException ioex)
    dataoutput.flush();
    datainput = new DataInputStream( socket.getInputStream() );
    servletoutput = response.getOutputStream();
    try
    byte[] outbytes = new byte[1024];
    datainput.read( outbytes );
    servletoutput.write( outbytes );
    catch(IOException ioex)
    servletoutput.flush();
    servletoutput.close();
    catch(Exception ex)
    // Server.java
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Server extends JFrame {
    private JTextField enter;
    private JTextArea display;
    DataOutputStream output;
    DataInputStream input;
    public Server()
    super( "Server" );
    Container c = getContentPane();
         enter = new JTextField();
         enter.setEnabled( false );
         c.add( enter, BorderLayout.SOUTH );
    display = new JTextArea();
    c.add( new JScrollPane( display ),
    BorderLayout.CENTER );
    setSize( 300, 150 );
    show();
    public void runServer()
    ServerSocket server;
    Socket connection;
    int counter = 1;
    try {
    // Step 1: Create a ServerSocket.
    server = new ServerSocket( 5000, 100 );
    while ( true ) {
    // Step 2: Wait for a connection.
    display.setText( "Waiting for connection\n" );
    connection = server.accept();
    display.append( "Connection " + counter +
    " received from: " +
    connection.getInetAddress().getHostName() );
    // Step 3: Get input and output streams.
    output = new DataOutputStream(
    connection.getOutputStream() );
    input = new DataInputStream(
    connection.getInputStream() );
    display.append( "\nGot I/O streams\n" );
    // Step 4: Process connection.
    String message =
    "SERVER>>> Connection successful";
    output.writeBytes( message );
    enter.setEnabled( true );
                   display.append( "\nConnected\n" );
    do {
    try {
                        byte[] mess = new byte[1024];
    input.read( mess );
    display.append( "\n" + message );
    display.setCaretPosition(
    display.getText().length() );
                   catch (IOException ioex )
    } while ( !message.equals( "CLIENT>>> TERMINATE" ) );
    // Step 5: Close connection.
    display.append( "\nUser terminated connection" );
    enter.setEnabled( false );
    output.close();
    input.close();
    connection.close();
    ++counter;
    catch ( EOFException eof ) {
    System.out.println( "Client terminated connection" );
    catch ( IOException io ) {
    io.printStackTrace();
    private void sendData( String s )
    try {
    output.writeBytes( "SERVER>>> " + s );
    display.append( "\nSERVER>>>" + s );
    catch ( IOException cnfex ) {
    display.append(
    "\nError writing object" );
    public static void main( String args[] )
    Server app = new Server();
    app.addWindowListener(
    new WindowAdapter() {
    public void windowClosing( WindowEvent e )
    System.exit( 0 );
    app.runServer();
    // Fig. 21.4: Client.java
    // Set up a Client that will read information sent
    // from a Server and display the information.
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.util.zip.*;
    public class Client extends Applet implements ActionListener {
    private TextField enter;
    private TextArea display;
    DataOutputStream output;
    DataInputStream input;
    private Button button, button2;
    URLConnection connection;
    private byte[] bytes1, bytes2;
    private String message, message2;
    public void init()
    setLayout( new BorderLayout() );
    enter = new TextField( " Enter text here " );
    enter.setEnabled( false );
    enter.addActionListener( this );
    add( enter, BorderLayout.NORTH );
    display = new TextArea( 4, 30 );
         display.setEditable( false );
    add( display, BorderLayout.CENTER );
         button = new Button( "Connect" );
         button.addActionListener( this );
         add( button, BorderLayout.SOUTH );
    public void runClient()
    Socket client;
    try {
    // Step 1: Create a Socket to make connection.
    display.setText( "Attempting connection\n" );
              URL currentpage = getCodeBase();
              String protocol = currentpage.getProtocol();
              String host = currentpage.getHost();
              int port = 8100;
              String urlsuffix = "/servlet/SocketServlet";
              URL dataurl = new URL( "http://localhost:8100/servlet/SocketServlet" );
              connection = dataurl.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Content-type", "application/octet-stream");
              connection.setUseCaches( false );
              display.append( "\nConnected to: " + host );          
    // Step 2: Get the output streams.
    output = new DataOutputStream(
    connection.getOutputStream() );
              display.append( "\n got output stream\n" );
              // Step 3 get input connection
              try
              display.append( "\nAttempting to connect to input stream\n" );
                   input = new DataInputStream( connection.getInputStream() );
                   bytes1 = new byte[1024];
                   input.readFully( bytes1 );
                   display.append( "\nGot input stream\n" );
                   message = new String( bytes1 );
                   display.append( "\n" + message + "\n" );          
              catch ( IOException ioex )
              // Step 3: Process connection.
              enter.setEnabled( true );
              do {
              try {
    bytes2 = new byte[1024];
              input.readFully( bytes2 );
              message2 = new String( bytes2 );
              display.append( "\n" + message2 );
              display.setCaretPosition(
              display.getText().length() );
              catch ( IOException ioex ) {
              display.append(
              "\nUnknown object type received" );
              } while ( !message.equals( "SERVER>>> TERMINATE" ) );
    // Step 4: Close connection.
    display.append( "Closing connection.\n" );
    output.close();
    input.close();
         catch (MalformedURLException mfe )
    catch ( EOFException eof ) {
    System.out.println( "Server terminated connection" );
    catch ( IOException e ) {
    e.printStackTrace();
    private void sendData( String s )
    try {
    message = s;
    output.writeBytes( "CLIENT>>> " + s );
    display.append( "\nCLIENT>>>" + s );
    catch ( IOException cnfex ) {
    display.append(
    "\nError writing object" );
    public void actionPerformed( ActionEvent e )
         if ( e.getActionCommand() == "Connect" )
              runClient();
         else
              sendData( e.getActionCommand() );
    public static void main(String args[])
    Frame f = new Frame("Chat Client");
         Client c = new Client();
         c.init();
         f.add("Center", c);
         f.setSize(300, 150);
         f.show();
    the connection appears to fail at client step 3, any help is super, thanks
    Aidan

    Hi,
    In your client you are trying to open OutputStream even though you are not using it.
    So there are two solutions here.
    1. If you dont need OutputStream your code shoud look like this
    try {
    // Step 1: Create a Socket to make connection.
    display.setText( "Attempting connection\n" );
    URL currentpage = getCodeBase();
    String protocol = currentpage.getProtocol();
    String host = currentpage.getHost();
    int port = 8100;
    String urlsuffix = "/servlet/SocketServlet";
    URL dataurl = new URL( "http://localhost:8100/servlet/SocketServlet" );
    connection = dataurl.openConnection();
    //connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Content-type", "application/octet-stream");
    connection.setUseCaches( false );
    display.append( "\nConnected to: " + host );
    // Step 2: Get the output streams.
    //output = new DataOutputStream(
    //connection.getOutputStream() );
    //display.append( "\n got output stream\n" );
    display.append( "\n Not interested in output stream\n" );
    //Step 3 Inpustream related
    // Step 4: Close connection.
    display.append( "Closing connection.\n" );
    //output.close();
    input.close();
    1. If you need OutputStream, close your OutputStream before even trying to get InputStream, your code should like this
    try {
    // Step 1: Create a Socket to make connection.
    display.setText( "Attempting connection\n" );
    URL currentpage = getCodeBase();
    String protocol = currentpage.getProtocol();
    String host = currentpage.getHost();
    int port = 8100;
    String urlsuffix = "/servlet/SocketServlet";
    URL dataurl = new URL( "http://localhost:8100/servlet/SocketServlet" );
    connection = dataurl.openConnection();
    //connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Content-type", "application/octet-stream");
    connection.setUseCaches( false );
    display.append( "\nConnected to: " + host );
    // Step 2: Get the output streams.
    output = new DataOutputStream(
    connection.getOutputStream() );
    display.append( "\n got output stream\n" );
    //I'll do whateve I've to do with outputstream
    //done with output stream closing
    output.close();
    //Step 3 Inpustream related
    // Step 4: Close connection.
    display.append( "Closing connection.\n" );
    //output.close();
    input.close();
    hope this works
    all the best,
    Raj

  • Applet failed to communicate with servlet for https, on tomcat5.0+apache2.0

    Hi
         I have a problem, we have a tomcat5.0 and apache 2.0 with jk connector, and an application where an applet comunicate to servlet.
    we need to set the ssl , the apache is configured with the ssl( openssl,).
    when I run the application with standalone tomcat with ssl
    connector (port 8443)enable, it runs fine for both http and https.
    i use httpsURLconnection for https communication from applet to servlet.
    But at production envoirment (Tomcat 5.0 , apache 2.0 and j connector with ssl enable at apache) it fails for https, all the jsps runs properly, but the applet isn't communicating with servlet. can anyone guess what is the problem.
    the exception dump is
    ava.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 401 SSL Connection Not Granted"
         at sun.net.www.protocol.http.HttpURLConnection.doTunneling(Unknown Source)
         at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
         at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
         at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
         at com.blu.HttpMessage.sendGetMessage(HttpMessage.java:65)
         at com.blu.HttpMessage.sendGetMessage(HttpMessage.java:38)
         at com.blu.applet.ServerDAO.sendDummyRequest(ServerDAO.java:66)

    Make sure your deployment is using a supported network configuration, we do not support running under localhost. Your SGD  server needs a valid DNS name configured.
    See
    2.1. SGD Server Requirements and Support
    for more details

  • Hasn't anyone out here worked with cut-through proxy

    hasn't enyone out here worked with cut-through proxy with acs. is there no one out here to help me out with cut-through proxy.
    sebastan

    Hi Sebastan,
    For your case, what's the scenario looks like?
    Rgds,
    AK

  • Http tunneling

    I'm facing some problems while doing http tunneling thru proxy and below I'm giving some trace messages.
    Without proxy the system seems to work ok.
    Client -------- proxy ------- Tunnel Server --------- Server
    The tunnel server tries to send back the data to client on the http connection.
    The client is trying to receive data on the http connection.
    The tunnel forwarder throws the following exception. Basically the tunnel forwarder thinks that the socket is closed immediately.
    java.net.SocketException: Socket closed
    at java.net.SocketOutputStream.socketWrite(Native Method)
    at java.net.SocketOutputStream.write(Unknown Source)
    at java.io.ObjectOutputStream.drain(Unknown Source)
    at java.io.ObjectOutputStream.setBlockData(Unknown Source)
    at java.io.ObjectOutputStream.writeObject(Unknown Source)
    at TunnelForwarder.run(TunnelForwarder.java:108)
    java.net.SocketException: Socket closed
    at java.net.SocketOutputStream.socketWrite(Native Method)
    at java.net.SocketOutputStream.write(Unknown Source)
    at java.io.ObjectOutputStream.drain(Unknown Source)
    at java.io.ObjectOutputStream.setBlockData(Unknown Source)
    at java.io.ObjectOutputStream.writeObject(Unknown Source)
    at TunnelForwarder.run
    The client throws the following exception. It thinks that the httpConnection is down immediately.
    java.net.SocketException: Unexpected end of file from server
    at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
    at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
    at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
    at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.plugin.protocol.jdk12.http.HttpURLConnection.getInputStream(Unknown Source)
    at TunnelReader.establishConnectionPath(TunnelReader.java:98)
    at TunnelReader.run(TunnelReader.java:124)
    java.lang.NullPointerException
    at TunnelReader.run(TunnelReader.java:130)
    However, the tunnel server shows that the tunnel is maintained
    And even the netstat -n shows that the connection exists
    C:\WINNT>netstat -n
    Active Connections
    Proto Local Address Foreign Address State
    |
    |
    TCP tunnelServer:3299 server:12000 ESTABLISHED
    |
    |
    TCP tunnelServer:9000 proxy:48040 ESTABLISHED
    |
    |
    The http connection is actually brought down by the proxy after a considerably long time (more than a minute).
    Regards,
    Rahuole pawer

    Do not try base your tunnel on urlConnections. After you send the message, you cannot read. The only way is to use 2 connections, because all the proxy servers support only HTTP/1.0, which was depricated by W3C in 1996 after HTTP/1.1 was accomplished. If your proxy does you are lucky. To make your tunnel working over HTTP/1.0 is terrible task of TCP stack rewriting in Java. May be someone has it implemented already. I am interested to look after.

  • HTTPS and a Proxy server?

    Does the plugin-in still not work with HTTPS and a proxy server?
    From plug-in docs -
    "Java Plug-in supports http, ftp, gopher and SOCKS v4 protocols through the proxy server. Currently, Java Plug-in does not support https (SSL). "

    Hello
    I am making HTTPS calls from within my applet code and this works fine using the basic Java Plug-in support for HTTPS.
    This means my code basically does:
    URL url = new URL("https://myhost.com/servlet/Test");
    URLConnection conn = url.openConnection();
    etc..
    We are using Java 1.4.2. I've read in the "How HTTPS Works in Java Plug-in" for 1.3, that the plugin uses the browsers API for making HTTPS connections. Is this still the case for 1.4?
    My basic problem is that it all works fine if the browser is NOT configured to use a proxy server. If a proxy server is configured we get the following Exception in the client:
    java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 400 Bad Request ( The data is invalid. )"
    I have read that "Sun's Java Secure Socket Extension (JSSE) library allows you to access a secure Web server from behind a firewall via proxy tunnelling. However, JSSE expects the proxy's reply to the tunnelling request to begin with "HTTP 1.0"; otherwise, it throws an IOException" (http://www.javaworld.com/javatips/jw-javatip111_p.html)
    The article talks about using the JSSE library but it seems to be assuming the client is an application not an applet.
    How do I use JSSE from within an applet if all the proxy information I seem to need to set in the JSSE code is held by the browser?
    Will JSSE support proxies returning responses beginning HTTP 1.1 in the future?
    Any help on this would be greatly appreciated.
    Many thanks
    mark

  • Http tunneling (t3 over http) doesn't work!!  (examples too)

    Hi,
    I'm trying to get http tunneling (t3 connection over http protocol) to work. I
    ran some examples included with Weblogic that try establishing that connection
    (PingTest, HelloApplet, SimpleT3Client), as well as my own test program, and they
    all give an error similar to this :
    Couldn't get a reference to server. Exception :
    javax.naming.CommunicationException. Root exception is java.net.ConnectException:
    No server found at HTTP://<IP>:<port>
    at weblogic.rjvm.RJVMFinder.findOrCreate(RJVMFinder.java:161) at weblogic.rjvm.ServerURL.findOrCreateRJVM(ServerURL.java:200)
    at weblogic.jndi.WLInitialContextFactoryDelegate.getInitialContext(WLInitialContextFactoryDelegate.java,
    Compiled Code) at weblogic.jndi.WLInitialContextFactoryDelegate.getInitialContext(WLInitialContextFactoryDelegate.java:148)
    at weblogic.jndi.WLInitialContextFactory.getInitialContext(WLInitialContextFactory.java:123)
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:671) at
    javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:242) at javax.naming.InitialContext.init(InitialContext.java:218)
    at javax.naming.InitialContext.<init>(InitialContext.java:194)
    (I replaced the actual Ip and port with <IP> and <port>).
    Now, the server is started and working at that ip and port - it services web http
    requests correctly, etc. Regular T3 connection (not over http) also works with
    it.
    Does anyone know the reason for this problem and/or how to fix it?
    Thanks, Leonid Portnoy

    It appears that one has to use the "Java Plugin" for this mode to work. The
    question is does the version of plugin need to be "in sync" with the JVM
    version on the server. ?.
    /rk
    "Adomas Svirskas" <[email protected]> wrote in message
    news:[email protected]...
    >
    It seems that the solution is to have these two lines in the
    properties file:
    weblogic.httpd.enable=true
    weblogic.httpd.tunnelingenabled=true
    Now it works.
    Thanks,
    Adomas
    "Adomas Svirskas" <[email protected]> wrote:
    Hi Leonid,
    Have you found a solution for this? I have these problems too.
    Thanks,
    Adomas
    "Leonid Portnoy" <[email protected]> wrote:
    Hi,
    I'm trying to get http tunneling (t3 connection over http protocol)to
    work. I
    ran some examples included with Weblogic that try establishing thatconnection
    (PingTest, HelloApplet, SimpleT3Client), as well as my own test program,
    and they
    all give an error similar to this :
    Couldn't get a reference to server. Exception :
    javax.naming.CommunicationException. Root exception is
    java.net.ConnectException:
    No server found at HTTP://<IP>:<port>
    at weblogic.rjvm.RJVMFinder.findOrCreate(RJVMFinder.java:161) atweblogic.rjvm.ServerURL.findOrCreateRJVM(ServerURL.java:200)
    atweblogic.jndi.WLInitialContextFactoryDelegate.getInitialContext(WLInitialCon
    textFactoryDelegate.java,
    Compiled Code) atweblogic.jndi.WLInitialContextFactoryDelegate.getInitialContext(WLInitialCon
    textFactoryDelegate.java:148)
    atweblogic.jndi.WLInitialContextFactory.getInitialContext(WLInitialContextFact
    ory.java:123)
    atjavax.naming.spi.NamingManager.getInitialContext(NamingManager.java:671)
    at
    javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:242)
    at javax.naming.InitialContext.init(InitialContext.java:218)
    at javax.naming.InitialContext.<init>(InitialContext.java:194)
    (I replaced the actual Ip and port with <IP> and <port>).
    Now, the server is started and working at that ip and port - it services
    web http
    requests correctly, etc. Regular T3 connection (not over http) alsoworks
    with
    it.
    Does anyone know the reason for this problem and/or how to fix it?
    Thanks, Leonid Portnoy

Maybe you are looking for