import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class SoapClient {
String SOAPUrl = null;
String SOAPPage = null;
String SOAPAction = null;
String cookie = null;
public SoapClient(String SOAPUrl,String SOAPPage, String SOAPAction, String cookie) {
this.SOAPUrl = SOAPUrl;
this.SOAPPage = SOAPPage;
this.SOAPAction = SOAPAction;
this.cookie = cookie;
}
public Document getResponse(String request) throws IOException, ParserConfigurationException, SAXException, KeyStoreException, NoSuchAlgorithmException, CertificateException, KeyManagementException {
Document doc = null;
if (SOAPUrl.startsWith(“http://”)) {
doc = getResponseWithHTTP(request);
} else {
doc = getResponseWithHTTPS(request);
}
return doc;
}
private Document getResponseWithHTTPS(String request) throws IOException, ParserConfigurationException, SAXException, KeyStoreException, NoSuchAlgorithmException, CertificateException, KeyManagementException {
String ReturnVal = null;
SSLSocket socket = getSecureSocket();
//SSLSocketFactory ssl = (SSLSocketFactory) SSLSocketFactory.getDefault();
//SSLSocket socket = (SSLSocket) ssl.createSocket(SOAPUrl, 443);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
PrintWriter pw = new PrintWriter(osw);
StringBuffer buf = new StringBuffer();
StringBuffer buf2 = new StringBuffer(request);
buf.append(“POST ” + SOAPPage + ” HTTP/1.1″ + “\r\n”);
buf.append(“Accept: */*” + “\r\n”);
if (SOAPAction!= null && !SOAPAction.equals(“”)) {
buf.append(“SOAPAction: “+ SOAPAction + “\r\n”);
}
buf.append(“Content-Type: text/xml; charset=utf-8″ + “\r\n”);
buf.append(“Content-Length: ” + buf2.length() + “\r\n”);
buf.append(“User-Agent: tJOPtJOPProxy/3.0″ + “\r\n”);
buf.append(“Host: ” + SOAPUrl + “\r\n”);
buf.append(“Connection: Keep-Alive” + “\r\n”);
buf.append(“Cache-Control: no-cache” + “\r\n”);
buf.append(“\r\n”);
buf.append(buf2.toString());
System.out.println(“———–”);
System.out.println(buf.toString());
System.out.println(“———–”);
pw.print(buf.toString());
pw.flush();
buf = new StringBuffer();
buf2 = null;
boolean DoLoop = true;
int Length = 0;
while(DoLoop) {
String str = br.readLine();
if(str.startsWith(“Content-Length:”)) {
String[] DataArray = str.split(” “);
Length = Integer.parseInt(DataArray[1]) + 2;
for(int i = 0; i < Length; i++) {
int c = br.read();
buf.append((char) c);
}
String data = buf.toString();
data = data.replaceAll(“&”, “&”);
ReturnVal = data;
DoLoop = false;
}
}
if (ReturnVal.startsWith(“\r\n”)) {
ReturnVal = ReturnVal.substring(“\r\n”.length());
}
System.out.println(“SOAP >> “+ReturnVal);
Document XMLDoc = XmlHelper.getXMLFromString(ReturnVal);
return XMLDoc;
}
private Document getResponseWithHTTP(String request) throws IOException, ParserConfigurationException, SAXException {
// Create the connection where we’re going to send the file.
System.setProperty(“java.protocol.handler.pkgs”, “com.sun.net.ssl.internal.www.protocol”);
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
URL url = new URL(SOAPUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
byte[] b = request.getBytes();
/*
POST /abservice/SharingService.asmx HTTP/1.1
SOAPAction: http://www.msn.com/webservices/AddressBook/FindMembership
Content-Type: text/xml; charset=utf-8
Cookie: MSPAuth=Removed
Host: contacts.msn.com
Content-Length: Variable
*/
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty(“SOAPAction”,SOAPAction);
httpConn.setRequestProperty(“Content-Type”,”text/xml; charset=utf-8″);
httpConn.setRequestProperty(“Cookie”,”MSPAuth=”+cookie);
httpConn.setRequestProperty( “Content-Length”, String.valueOf( b.length ) );
httpConn.setRequestMethod( “POST” );
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
// Everything’s set up; send the XML that was read in to b.
OutputStream out = httpConn.getOutputStream();
out.write( b );
out.close();
// Read the response and write it to standard out.
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
String inputLine = “”;
String input = null;
while ((input = in.readLine()) != null) inputLine+=input+”\r\n”;
in.close();
Document XMLDoc = XmlHelper.getXMLFromString(inputLine);
return XMLDoc;
}
private SSLSocket getSecureSocket() throws FileNotFoundException, KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException {
String host= SOAPUrl;
int port = 443;
char[] passphrase;
String p = “changeit”;
passphrase = p.toCharArray();
File file = new File(“jssecacerts”);
if (file.isFile() == false) {
char SEP = File.separatorChar;
File dir = new File(System.getProperty(“java.home”) + SEP
+ “lib” + SEP + “security”);
file = new File(dir, “jssecacerts”);
if (file.isFile() == false) {
file = new File(dir, “cacerts”);
}
}
InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close();
SSLContext context = SSLContext.getInstance(“TLS”);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[] {tm}, null);
SSLSocketFactory factory = context.getSocketFactory();
SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
socket.setSoTimeout(10000);
// try {
// System.out.println(“Starting SSL handshake…”);
// socket.startHandshake();
// socket.close();
// System.out.println();
// System.out.println(“No errors, certificate is already trusted”);
// } catch (SSLException e) {
// System.out.println();
// e.printStackTrace(System.out);
// }
//
// X509Certificate[] chain = tm.chain;
// if (chain == null) {
// System.out.println(“Could not obtain server certificate chain”);
// return null;
// }
//
// BufferedReader reader =
// new BufferedReader(new InputStreamReader(System.in));
//
// System.out.println();
// System.out.println(“Server sent ” + chain.length + ” certificate(s):”);
// System.out.println();
// MessageDigest sha1 = MessageDigest.getInstance(“SHA1″);
// MessageDigest md5 = MessageDigest.getInstance(“MD5″);
// for (int i = 0; i < chain.length; i++) {
// X509Certificate cert = chain[i];
// System.out.println
// (” ” + (i + 1) + ” Subject ” + cert.getSubjectDN());
// System.out.println(” Issuer ” + cert.getIssuerDN());
// sha1.update(cert.getEncoded());
// System.out.println(” sha1 ” + toHexString(sha1.digest()));
// md5.update(cert.getEncoded());
// System.out.println(” md5 ” + toHexString(md5.digest()));
// System.out.println();
// }
//
// System.out.println(“Enter certificate to add to trusted keystore or ‘q’ to quit: [1]“);
// String line = “1″;
// int k;
// try {
// k = (line.length() == 0) ? 0 : Integer.parseInt(line) – 1;
// } catch (NumberFormatException e) {
// System.out.println(“KeyStore not changed”);
// return null;
// }
//
// X509Certificate cert = chain[k];
// String alias = host + “-” + (k + 1);
// ks.setCertificateEntry(alias, cert);
//
// OutputStream out = new FileOutputStream(“jssecacerts”);
// ks.store(out, passphrase);
// out.close();
//
// System.out.println();
// System.out.println(cert);
// System.out.println();
// System.out.println
// (“Added certificate to keystore ‘jssecacerts’ using alias ‘”
// + alias + “‘”);
return socket;
}
private static final char[] HEXDIGITS = “0123456789abcdef”.toCharArray();
private static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 3);
for (int b : bytes) {
b &= 0xff;
sb.append(HEXDIGITS[b >> 4]);
sb.append(HEXDIGITS[b & 15]);
sb.append(‘ ‘);
}
return sb.toString();
}
private static class SavingTrustManager implements X509TrustManager {
private final X509TrustManager tm;
private X509Certificate[] chain;
SavingTrustManager(X509TrustManager tm) {
this.tm = tm;
}
public X509Certificate[] getAcceptedIssuers() {
throw new UnsupportedOperationException();
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
throw new UnsupportedOperationException();
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
this.chain = chain;
tm.checkServerTrusted(chain, authType);
}
}
}