1 package net.matuschek.http.connection; 2 3 6 7 import java.io.IOException ; 8 import java.io.InputStream ; 9 import java.io.OutputStream ; 10 import java.io.UnsupportedEncodingException ; 11 import java.net.InetAddress ; 12 import java.net.Socket ; 13 14 import javax.net.ssl.SSLSocket; 15 import javax.net.ssl.SSLSocketFactory; 16 17 22 23 24 30 public class HttpsHelper { 31 32 33 boolean useProxy = false; 34 35 36 InetAddress proxyHost = null; 37 38 39 int proxyPort = 0; 40 41 42 43 46 public HttpsHelper() { 47 } 48 49 50 54 public HttpsHelper(InetAddress proxyHost, int proxyPort, boolean useProxy) { 55 this.proxyHost = proxyHost; 56 this.proxyPort = proxyPort; 57 this.useProxy = useProxy; 58 } 59 60 61 62 73 public HttpConnection createHttpsConnection(String host, int port) 74 throws IOException 75 { 76 HttpConnection connection = null; 77 SSLSocketFactory factory = (SSLSocketFactory)SSLSocketFactory.getDefault(); 78 SSLSocket socket = null; 79 80 if (! useProxy) { 81 82 socket = (SSLSocket)factory.createSocket(host,port); 83 84 } else { 85 86 Socket tunnel = new Socket (proxyHost, proxyPort); 87 doTunnelHandshake(tunnel, host, port); 88 89 92 socket = (SSLSocket)factory.createSocket(tunnel, host, port, true); 93 94 100 socket.startHandshake(); 101 } 102 103 connection = new HttpConnection(socket); 104 105 return connection; 106 107 } 108 109 110 114 private void doTunnelHandshake(Socket tunnel, String host, int port) 115 throws IOException 116 { 117 OutputStream out = tunnel.getOutputStream(); 118 String msg = "CONNECT " + host + ":" + port + " HTTP/1.0\n" 119 + "User-Agent: JoBo/1.4beta" 120 + "\r\n\r\n"; 121 byte[] b; 122 try { 123 127 b = msg.getBytes("ASCII7"); 128 } catch (UnsupportedEncodingException ignored) { 129 133 b = msg.getBytes(); 134 } 135 out.write(b); 136 out.flush(); 137 138 142 byte[] reply = new byte[200]; 143 int replyLen = 0; 144 int newlinesSeen = 0; 145 boolean headerDone = false; 146 147 InputStream in = tunnel.getInputStream(); 148 while (newlinesSeen < 2) { 149 int i = in.read(); 150 if (i < 0) { 151 throw new IOException ("Unexpected EOF from proxy"); 152 } 153 if (i == '\n') { 154 headerDone = true; 155 ++newlinesSeen; 156 } else if (i != '\r') { 157 newlinesSeen = 0; 158 if (!headerDone && replyLen < reply.length) { 159 reply[replyLen++] = (byte) i; 160 } 161 } 162 } 163 164 169 String replyStr; 170 try { 171 replyStr = new String (reply, 0, replyLen, "ASCII7"); 172 } catch (UnsupportedEncodingException ignored) { 173 replyStr = new String (reply, 0, replyLen); 174 } 175 176 177 if (!replyStr.startsWith("HTTP/1.0 200")) { 178 throw new IOException ("Unable to tunnel through proxy" 179 + ". Proxy returns \"" + replyStr + "\""); 180 } 181 182 183 } 184 185 186 187 } 188 | Popular Tags |