1 package com.jcommercesql.gateway.authorizenet; 2 3 23 24 import java.io.*; 25 import javax.net.ssl.*; 26 27 public class Gateway { 28 29 private String method = null; private String host = null; 31 private int port=443; 32 private String path=null; 33 private byte[] data = null; 34 35 private static int READSIZE=10000; 36 37 public Gateway() {} 38 39 protected byte[] submitGet(String host, int port, String path) 41 throws Exception { 42 this.host=host; 43 this.port=port; 44 if ( path==null || path.equals("") ) { 45 path="/"; } 46 else { 47 this.path=path; } 49 method="GET"; 50 return(submit()); 51 } 52 53 protected byte[] submitPost(String host, int port, String path, String data) 55 throws Exception { 56 return submitPost(host,port,path,data.getBytes()); 57 } 58 59 protected byte[] submitPost(String host, int port, String path, byte[] data) 61 throws Exception { 62 63 this.host=host; 64 this.port=port; 65 if ( path==null || path.equals("") ) { 66 path="/"; } 67 else { 68 this.path=path; } 70 if (data==null) { data = new byte[1]; } this.data=data; 72 method="POST"; 73 return(submit()); 74 } 75 76 private byte[] submit() throws Exception { 78 79 int bytesRead = 0; 80 byte[] result = null; 81 byte[] temp = null; 82 83 ByteArrayOutputStream sendBytes = new ByteArrayOutputStream(); 84 ByteArrayOutputStream receiveBytes = new ByteArrayOutputStream(); 85 86 try { 87 SSLSocketFactory factory=(SSLSocketFactory)SSLSocketFactory.getDefault(); 88 SSLSocket socket = (SSLSocket)factory.createSocket(host,port); 89 socket.startHandshake(); 90 91 OutputStream socketOut =( socket.getOutputStream() ); 92 93 String command = method+" "+path+" HTTP/1.0\n"; 94 96 if (data!=null) { 97 command+="Content-Length: " + data.length +"\n\n"; 98 sendBytes.write(command.getBytes(),0,command.length()); 99 sendBytes.write(data,0,data.length); 100 } else { 101 sendBytes.write(command.getBytes(),0,command.length()); 103 } 104 105 sendBytes.write("\n".getBytes(),0,"\n".length()); 106 107 temp = sendBytes.toByteArray(); 108 socketOut.write(temp,0,temp.length); 109 socketOut.flush(); 110 111 112 BufferedInputStream socketIn = 113 new BufferedInputStream( socket.getInputStream() ); 114 115 byte[] inputData = new byte[READSIZE]; 116 while ((bytesRead=socketIn.read(inputData,0,READSIZE)) > -1) { 117 receiveBytes.write(inputData,0,bytesRead); 118 } 119 result=receiveBytes.toByteArray(); 120 121 receiveBytes.close(); 122 sendBytes.close(); 123 socket.close(); 124 125 } catch (Exception e) { 126 throw e; 127 } 128 129 return result; 130 } 132 } | Popular Tags |