Can any body help me in reading from HTTPS URL

I need to read an HTTPS URL and store the response within a table .
How will I manage to do it from within a servlet using URLConnection and openStream as it does'nt work .
How will JSSE help in this regard .
Since I also need to give the userid and password to get into the file and read the file
https://anyhost.com/readthisfile.html
somnath
Web Developer

Hi,
The Java Secure Socket Extension (JSSE) library from Sun Microsystems lets you access a secure Web server from behind a firewall via
proxy tunneling. To do this, the JSSE application needs to set the https.ProxyHost and https.ProxyPort system properties. The
tunneling code in JSSE checks for "HTTP 1.0" in the proxy's response. If your proxy, like many, returns "HTTP 1.1", you will get an
IOException. In this case, you need to implement your own HTTPS tunneling protocol.
In this article, I will show you how to create a secure socket that tunnels through the firewall, and pass it to the HTTPS stream handler to
open HTTPS URLs using the URLConnection class.
Open the http tunnel socket to the proxy
The first step to creating your secure socket is to open the tunneling socket to the proxy port. The code needed to do this proxy
handshaking can be found in the sample code SSLClientSocketWithTunneling.java that comes with the JSSE distribution. First, a normal socket is created that connects to
the proxy port on the proxy host (line 65). After the socket is created, it is passed to the doTunnelHandshake() method where the proxy's tunneling protocol is called:
54 SSLSocketFactory factory =
55 (SSLSocketFactory)SSLSocketFactory.getDefault();
56
57 /*
58 * Set up a socket to do tunneling through the proxy.
59 * Start it off as a regular socket, then layer SSL
60 * over the top of it.
61 */
62 tunnelHost = System.getProperty("https.proxyHost");
63 tunnelPort = Integer.getInteger("https.proxyPort").intValue();
64
65 Socket tunnel = new Socket(tunnelHost, tunnelPort);
66 doTunnelHandshake(tunnel, host, port);
In doTunnelHandshake(), an http "CONNECT" command is sent to the proxy, with the secure site's hostname and port number as the parameters (line 161). In the original
tunneling code on line 206 in JSSE, it then checks for "HTTP/1.0 200" in the proxy's reply. If your organization's proxy replies with "HTTP 1.1", an IOException will be
thrown. To get around this, the code here checks for the reply "200 Connection Established", which indicates that tunneling is successful (line 207). You can modify the
code to check for the expected corresponding response from your proxy:
139 private void doTunnelHandshake(Socket tunnel, String host, int port)
140 throws IOException
141 {
142 OutputStream out = tunnel.getOutputStream();
143 String msg = "CONNECT " + host + ":" + port + " HTTP/1.0\n"
144 + "User-Agent: "
145 + sun.net.www.protocol.http.HttpURLConnection.userAgent
146 + "\r\n\r\n";
147 byte b[];
148 try {
149 /*
150 * We really do want ASCII7 -- the http protocol doesn't change
151 * with locale.
152 */
153 b = msg.getBytes("ASCII7");
154 } catch (UnsupportedEncodingException ignored) {
155 /*
156 * If ASCII7 isn't there, something serious is wrong, but
157 * Paranoia Is Good (tm)
158 */
159 b = msg.getBytes();
160 }
161 out.write(b);
162 out.flush();
163
164 /*
165 * We need to store the reply so we can create a detailed
166 * error message to the user.
167 */
168 byte reply[] = new byte[200];
169 int replyLen = 0;
170 int newlinesSeen = 0;
171 boolean headerDone = false; /* Done on first newline */
172
173 InputStream in = tunnel.getInputStream();
174 boolean error = false;
175
176 while (newlinesSeen < 2) {
177 int i = in.read();
178 if (i < 0) {
179 throw new IOException("Unexpected EOF from proxy");
180 }
181 if (i == '\n') {
182 headerDone = true;
183 ++newlinesSeen;
184 } else if (i != '\r') {
185 newlinesSeen = 0;
186 if (!headerDone && replyLen < reply.length) {
187 reply[replyLen++] = (byte) i;
188 }
189 }
190 }
191
192 /*
193 * Converting the byte array to a string is slightly wasteful
194 * in the case where the connection was successful, but it's
195 * insignificant compared to the network overhead.
196 */
197 String replyStr;
198 try {
199 replyStr = new String(reply, 0, replyLen, "ASCII7");
200 } catch (UnsupportedEncodingException ignored) {
201 replyStr = new String(reply, 0, replyLen);
202 }
203
204 /* We check for Connection Established because our proxy returns
205 * HTTP/1.1 instead of 1.0 */
206 //if (!replyStr.startsWith("HTTP/1.0 200")) {
207 if(replyStr.toLowerCase().indexOf(
208 "200 connection established") == -1){
209 throw new IOException("Unable to tunnel through "
210 + tunnelHost + ":" + tunnelPort
211 + ". Proxy returns \"" + replyStr + "\"");
212 }
213
214 /* tunneling Handshake was successful! */
215 }
Overlay http tunnel socket with SSL socket
After you have successfully created the tunneling socket, you overlay it with the SSL socket. Again, this is not difficult to do:
54 SSLSocketFactory factory =
55 (SSLSocketFactory)SSLSocketFactory.getDefault();
56
57 /*
58 * Set up a socket to do tunneling through the proxy.
59 * Start it off as a regular socket, then layer SSL
60 * over the top of it.
61 */
62 tunnelHost = System.getProperty("https.proxyHost");
63 tunnelPort = Integer.getInteger("https.proxyPort").intValue();
64
65 Socket tunnel = new Socket(tunnelHost, tunnelPort);
66 doTunnelHandshake(tunnel, host, port);
67
68 /*
69 * Ok, let's overlay the tunnel socket with SSL.
70 */
71 SSLSocket socket =
72 (SSLSocket)factory.createSocket(tunnel, host, port, true);
73
74 /*
75 * register a callback for handshaking completion event
76 */
77 socket.addHandshakeCompletedListener(
78 new HandshakeCompletedListener() {
79 public void handshakeCompleted(
80 HandshakeCompletedEvent event) {
81 System.out.println("Handshake finished!");
82 System.out.println(
83 "\t CipherSuite:" + event.getCipherSuite());
84 System.out.println(
85 "\t SessionId " + event.getSession());
86 System.out.println(
87 "\t PeerHost " + event.getSession().getPeerHost());
88 }
89 }
90 );
The code had called the SSLSocketFactory's getDefault() method earlier to get an instance of the SSLSocketFactory (line 54, repeated above). Next, it passes the
tunneling socket that was created in the previous step to the createSocket() method of the SSLSocketFactory. The createSocket() method returns an SSLSocket that is
connected to the destination host and port via the proxy tunnel. You can optionally add a HandshakeCompletedListener to the socket if you wish to be informed when the
SSL handshaking is completed.
The SSLSocket created is basically ready for use to transfer secure contents. The startHandshake() method is called to start the SSL handshaking (line 98). After which, you
can issue the http "GET" command to retrieve the secure pages (line 105):
91
92 /*
93 * send http request
94 *
95 * See SSLSocketClient.java for more information about why
96 * there is a forced handshake here when using PrintWriters.
97 */
98 socket.startHandshake();
99
100 PrintWriter out = new PrintWriter(
101 new BufferedWriter(
102 new OutputStreamWriter(
103 socket.getOutputStream())));
104
105 out.println("GET http://www.verisign.com/index.html HTTP/1.0");
106 out.println();
107 out.flush();
However, issuing http commands to the tunneling SSL socket to access Webpages is not ideal because it would mean having to rewrite the whole http protocol handler from
scratch. Instead, you should use the HTTPS URL APIs that the JSSE already includes for that purpose. To do this, you have to pass the tunneling SSL socket to the HTTPS URL
stream handler.
Pass SSL socket to HTTPS URL stream handler
The JSSE library has an HttpsURLConnection class that is in the com.sun.net.ssl package, which extends the java.net.URLConnection class. An HttpsURLConnection object
is returned by the URL object's openConnection() method when "HTTPS" is specified as the protocol. The HttpsURLConnection class has a method, setSSLSocketFactory(),
that lets you set an SSLSocketFactory of your choice. To pass the tunneling SSL socket to the HTTPS URL stream handler, you would set the setSSLSocketFactory()
method's parameter with a socket factory that returns the tunneling SSL socket that you created previously.
To do this, you would wrap the code discussed previously in an SSLTunnelSocketFactory class that extends from the SSLSocketFactory class. The SSLSocketFactory is an
abstract class. To extend it, you must implement the createSocket() method to return the tunneling SSL socket that you created earlier:
12 public SSLTunnelSocketFactory(String proxyhost, String proxyport){
13 tunnelHost = proxyhost;
14 tunnelPort = Integer.parseInt(proxyport);
15 dfactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
16 }
44 public Socket createSocket(Socket s, String host, int port,
45 boolean autoClose)
46 throws IOException,UnknownHostException
47 {
48
49 Socket tunnel = new Socket(tunnelHost,tunnelPort);
50
51 doTunnelHandshake(tunnel,host,port);
52
53 SSLSocket result = (SSLSocket)dfactory.createSocket(
54 tunnel,host,port,autoClose);
55
56 result.addHandshakeCompletedListener(
57 new HandshakeCompletedListener() {
58 public void handshakeCompleted(HandshakeCompletedEvent event) {
59 System.out.println("Handshake finished!");
60 System.out.println(
61 "\t CipherSuite:" + event.getCipherSuite());
62 System.out.println(
63 "\t SessionId " + event.getSession());
64 System.out.println(
65 "\t PeerHost " + event.getSession().getPeerHost());
66 }
67 }
68 );
69
70 result.startHandshake();
71
72 return result;
73 }
Notice that the SSLTunnelSocketFactory contains a default SSLSocketFactory object. The default SSLSocketFactory object can be instantiated from a call to the static
method getDefault() (line 15). You need this SSLSocketFactory object to overlay the tunnel socket with the SSL socket, as discussed earlier. You also call the default
object's getDefaultCipherSuites() and getSupportedCipherSuites() methods when implementing the corresponding abstract methods of the SSLSocketFactory super
class. For implementation details, please refer to the complete source code for the SSLTunnelSocketFactory in Resources.
Tunnel through the proxy via URLConnection
To tunnel through the proxy via URLConnection in your JSSE application, after you call the openConnection() method, check if the returned object is that of the
HttpsURLConnection. If so, you instantiate your SSLTunnelSocketFactory object and set it in the setSSLSocketFactory() method (lines 22 through 25):
10 public class URLTunnelReader {
11 private final static String proxyHost = "proxy.sg.ibm.com";
12 private final static String proxyPort = "80";
13
14 public static void main(String[] args) throws Exception {
15 System.setProperty("java.protocol.handler.pkgs",
16 "com.sun.net.ssl.internal.www.protocol");
17 //System.setProperty("https.proxyHost",proxyHost);
18 //System.setProperty("https.proxyPort",proxyPort);
19
20 URL verisign = new URL("https://www.verisign.com");
21 URLConnection urlc = verisign.openConnection(); //from secure site
22 if(urlc instanceof com.sun.net.ssl.HttpsURLConnection){
23 ((com.sun.net.ssl.HttpsURLConnection)urlc).setSSLSocketFactory
24 (new SSLTunnelSocketFactory(proxyHost,proxyPort));
25 }
26
27 BufferedReader in = new BufferedReader(
28 new InputStreamReader(
29 urlc.getInputStream()));
30
31 String inputLine;
32
33 while ((inputLine = in.readLine()) != null)
34 System.out.println(inputLine);
35
36 in.close();
37 }
38 }
You can then access the HTTPS URLs using the APIs provided by the URLConnection class. You don't need to worry about the format of the http GET and POST commands,
which you would if you used the SSL Socket APIs.
The complete source code for the SSLTunnelSocketFactory and the application code that connects to a secure URL using proxy tunneling is included in Resources. To
compile and run the application, you would need to download and install Sun's JSSE from its Website, also listed in Resources.
Conclusion
If your JSSE application could not tunnel through your organization's firewall, you need to implement your own tunneling socket. The sample code included with the JSSE
distribution shows you how to open an SSL socket tunnel. This article goes one step further to show you how to pass the tunneling socket to the HTTPS URL stream handler,
and saves you the trouble of rewriting a http handler
I hope this will help you.
Thanks
Bakrudeen

Similar Messages

  • I am trying to find a driver to syn mini mac to Lexmark x9350. Can any body help please?

    I am trying to find a driver to syn mini mac to Lexmark x9350. Can any body help please?

    Humm... the only Lexmark X9300 download that I see is for SL 10.6...?
    Lexmark United States Support & Downloads for Lexmark X9350
    I'm not sure exactly what "component missing" means, but it sounds more like a missing driver than a missing printer part? 
    To be honest, I think your going to have to remove all previous Lexmark drivers and software from your system, temporarily connect the printer up USB and use the system updater as per the link that I posted in my first reply.
    Lexmark United States
    You might also check to see if you have a failed print job..?
    Open the Print & Fax Preferences and select Open Print Queue...
    Pause the Printer using the green button.
    Select (highlight) each of the jobs in Status and Delete them all.  
    Resume Printer using the green button and send it a new job.

  • I have to install Oracle 9.2 on Solaris 9 I have no clue can any body help

    I have to install Oracle 9.2 on Solaris 9 I have no clue can any body help me I havent installed oracle on any Unix based system only done on Windows based by running the oracle installer can any one guide me how to accomplish this Task. any detailed step by step how to install from CD drive how to mount it. Please reply
    Thanks

    Hi,
    <br></br>
    <br>You can help with this doc Oracle9i Installation Guide Release 2 (9.2.0.1.0) for UNIX Systems: AIX-Based Systems, Compaq Tru64 UNIX, HP 9000 Series HP-UX, Linux Intel, and Sun Solaris</br>
    <br>Bests reagards,</br>
    <br>Nicolas</br>

  • My Imac is ejecting every disk inserted in it, I cannot access the disks, can any body help me troubleshoot the problem. I am using snow leopard.

    My Imac is ejecting every disk inserted in it, I cannot access the disks, can any body help me troubleshoot the problem. I am using snow leopard.

    Try resetting the SMC Intel-based Macs: Resetting the System Management Controller (SMC) - Apple Support
    and PRAM How to Reset NVRAM on your Mac - Apple Support
    If those don't help you can try a cleaning disc or a quick shot of compressed air. Chances are that your drive has failed, join the club it's not all that uncommon. You can either have it replaced or purchase an inexpensive external drive. Don't buy the cute little Apple USB Superdrive, it won't work on macs with internal drives working or not.

  • My Imac is ejecting every disk inserted in it, I cannot access the disks, can any body help me troubleshoot the problem.

    My Imac is ejecting every disk inserted in it, I cannot access the disks, can any body help me troubleshoot the problem

    The frist thing to try is a drive-n disk. They are cheap (US$5-15) and easy to use. Many unresponsive drives, even ones declared "dead" by an Apple tech, have returned to service after a cleaning.
    Check with home entertainment specialty shops, electronic superstores and office supply outlets that sell computer accessories.

  • Please can any body help me out where can I find link to download  ALDSP2.5

    Hi All,
    Please can any body help me out where can I find link to download ALDSP2.5.
    I am trying since last couple of days as I am not able to find it. please some body help me out in this regard. I appriciate even if I get a link to download ALDSP3.0.
    thanks in advance.
    Please mail me the links at [email protected]
    rajen.
    Edited by: user13358281 on Jul 2, 2010 2:57 PM

    Hello Werner,
    Thanks for response, but I couldn't find the same.
    Still my search is going on. I dont know why oracle people made this that dificult, If I am not wrong I think earlier i could easily locate the previous version artifacts(softwares) easily. but now why they made that complicated.. no clues.
    any ways thanks once again.

  • TS1538 hi i updated my iphone 4 with itunes and now i cannot use my phone as i keep getting error 16 after trying to restore my phone....i cannot afford to replace ..can any body help me...the phone is out of warrenty so apple do not want to know....pleas

    hi i updated my iphone 4 with itunes and now i cannot use my phone as i keep getting error 16 after trying to restore my phone....i cannot afford to replace ..can any body help me...the phone is out of warrenty so apple do not want to know....please any help

    https://discussions.apple.com/message/23100453#23100453
    more hits from the search
    https://www.google.dk/search?q=restore+itphone+error+16&oq=restore+itphone+error +16&aqs=chrome..69i57j0l5.11485j0j7&sourceid=chrome&espv=210&es_sm=93&ie=UTF-8

  • Can any body help me to prepare f.s for!

    can any body help me to prepare f.s for!
    all material movements and asociated accoutning document?
    all open purchase orders for a given plant and delivery period?

    Hi
    what do you mean by f.s, is it functional specification?
    Material document associated accounting document you can find MSEG and BSEG tables
    Open Purchase Orders for a given plant and delivery period
    Purchase orders infirmation is available in EKKO (Header) and EKPO (Item)
    Take the information from EKKO by company code, pass it on to EKPO by plant (WERKS)which is not equal to (EKPO -ELIKZ) for open PO and for delivery date (EKET-EINDT).
    please check and let me know if you need anything.
    regards
    Srinivas

  • On my macbook pro when opening a page i can not save it as a pdf only give me the option of saving it as a web page can any body help me on this I have tryed so many times without success

    on my macbook pro when opening a page on safaryi can not save it as a pdf only give me the option of saving it as a web page can any body help me on this I have tryed so many times without success?

    Just select Print in Safari and then, in the bottom left-hand corner, select PDF and you can save it to whichever flavor pdf file you like.
    Clinton

  • TS3694 i forgot the password of my  iphone 3g and when i try to restore it it shows the message"my iphone 3g could not be restored an unknown error occurred(1015)" can any body help please..

    i forgot the password of my  iphone 3g and when i try to restore it it shows the message"my iphone 3g could not be restored an unknown error occurred(1015)" can any body help please..

    This error normally appears if you attempted to downgrade or modify your iOS. See here http://support.apple.com/kb/TS3694#error1015

  • HT4061 I can not connect to ITunes Store to download updates. I have no trouble connecting to the internet. It worked OK up to about a last month. can any body help.

    I can not connect to ITunes Store to download updates. I have no trouble connecting to the internet. It worked OK up to about a last month. can any body help.

    Hi there bigyellowdigger!
    I have an article here that can help you troubleshoot this issue with your connection to the iTunes Store. That article can be found right here:
    Can't connect to the iTunes Store
    http://support.apple.com/kb/ts1368
    Take care, and thanks for visiting the Apple Support Communities.
    -Braden

  • I have a brand new i phone 4s and i have updated the soft ware to the 5.1 and tried to restore it to download my old contacts and apps etc. and my computer now wont recognise my phone and itunes will not do anything can any body help please????

    I have a brand new i phone 4s and i have updated the soft ware to the 5.1 and tried to restore it to download my old contacts and apps etc. and my computer now wont recognise my phone and itunes will not do anything can any body help please???? i need this sorting asap xxxxxxx

    see if this link helps   http://support.apple.com/kb/TS1538

  • How to recover emails from Mail after account is deleted accidentally. All my emails are now gone and i am standing no where. Can any body help me out by recovering my emails.

    After having problem in getting emails from pop server, i thought of removing account and adding it again. Problem was solved but all my previous emails are gone.
    Really needed all my emails back. Tried but could went through. Also purchased once software "EaseUS", no further progress was achieved. It only recovered deleted emails which was of no significance for me.
    Can any one help me out. I have no "Time Machine" active on my mac book pro.

    Hi Roger
    Thank you for your reply.
    My original feed is: http://casa-egypt.com/feed/
    However, because I modified the feed http://feeds.feedburner.com/imananddinasbroadcast and nothing changed, I redirected it to another feed and then I deleted this feed.
    Is there any way to change the feed in itunes? The only feed I have now is  http://feeds.feedburner.com/CasaEgyptStation
    I tried to restore the feed http://feeds.feedburner.com/imananddinasbroadcast but feedburner refused.
    I know that I missed things up but I still have hope in working things out.
    Thanks is advance.
    Dina
    Message was edited by: dinadik

  • Can any body help me in creating a jar using Weblogic server tool

    I have created the class files of the container manged bean successfully.I want to create the jar file using the weblogic tool.
    I have created a new jar file and now I have to add a bean class file and a home class file to it.In the tool I choose a the path using the choose button.When I say next it complaints that it cannot locate the bean files.
    Can any body please help me soon..
    waiting for your reply.

    I had similar problems with the WLS deploy tool. I think they were solved by making sure that I started the tool from the directory that contained the root package of my EJBs.
    It might work...

  • My macbook (born 2006, mac os x snowleopard) broke down. I started again with DVD, but can not find hard disc, to repair it - can any body help me, pleeeeease?

    first time, using that way looking for help (in former times I get it directly from apple...). My problem: my macbook was getting more and more slowly, I turned it off an after turning on again, there was only a question mark. after starting with system-DVD, I could not find the hard disc to repaire it with first aid or do any thng else. I´m writing with macbook pro of my daughter now and ugentnly need to start my macbook as soon as possible. could any body help me??? (sorry, my english is a not so well) andrea from berlin

    Since you have the system disks, you can try running the Apple Hardware Test, that should confirm if the drive is dead or not. You'll use the disk that says 'AHT Version x.x' in small print on the label.

Maybe you are looking for

  • BPM Performance issue

    Hi there,    Please help me ASAP with the following issue, as this is Production problem:    We are using BPM Collect pattern using time to collect IDocs into a file. For small # of IDocs (upto 1500 messages) this is working fine.    For a load of 30

  • Activesync doesn't work - How to use Windows bluetooth driver?

    Well, I have nearly given up on trying to get the Toshiba Bluetooth stack to work with my QTek PDA Phone. The reason for this is that the stack does not correctly enumerate all the functions of the device and therefore I can't configure the activesyn

  • Safari Update Sending my MBP into Spasms?!

    I have a latest gen Macbook Pro. I installed the latest Safari Security update (3.1.1 I believe) and rebooted the system before starting to work this morning. On reboot it started behaving erratically. I don't know if all of these symptoms are relate

  • Error on import abap phase(ecc6.0 on db2)

    Hi,    Iam getting error on import abap phase : the transaction log for database is full. SQLSTATE=57011. my log dirs are available space.guide me for same to resolve the issue. Thanku

  • Putting slideshow on TV for presentation

    Hi I'm wondering if it's possible to put my slideshows on my TV to make a presentation. complete with songs and all that. How would I go about doing this?