1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
| import UI.Composent.AppletAWS.AppletAWS;
import aws.apache.http.entity.mime.content.FileBody;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* A free Java sample program to POST to a HTTPS secure SSL website.
* Free for use as long as this comment is included in the program as it is.
* @see http://www.java-samples.com/showtutorial.php?tutorialid=1343
* @see http://www.java-samples.com for more Free Java programs available for download
*
* Pour tous ce qui touche aux contexte SSL :
* @see http://www.developpez.net/forums/d246453/java/developpement-web-java/web-services/connexion-java-client-serveur-https-via-proxy/#post2227955
* @author William Alexander
*/
public class HttpsPost {
private final String _certPath = "/path/to/my/certificate.p12"; // Le chemin vers le certificat.
private final char[] _certPass = "certPass".toCharArray(); // Le mot de passe du certificat.
private final char[] _keyStorePass = "keyStorePass".toCharArray(); // Le mot de passe du KeyStore.
private HttpsURLConnection _connection;
private String _query;
private String _response;
/**
* Constructeur. Initialise la connexion HTTPS.
* @param url l'URL à laquelle se connecter
* @param proxysList la liste des proxys détectés
*/
public HttpsPost(String url, ArrayList<Proxy> proxysList) {
this._query = "";
this._response = "";
try {
// System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
// java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
// On récupère le certificat.
InputStream certInput = AppletAWS.frame.getClass().getResourceAsStream(this._certPath);
// Création d'un KeyStore PKCS12.
KeyStore ksP12 = KeyStore.getInstance("PKCS12");
ksP12.load(certInput, this._certPass); // Ajout du certificat dans ce KeyStore.
String alias = ""; // Va contenir l'alias du certificat.
// Récupération de l'alias.
Enumeration aliases = ksP12.aliases();
while (aliases.hasMoreElements())
alias = (String) aliases.nextElement();
KeyStore ksJks = KeyStore.getInstance("JKS"); // Création d'un KeyStore Java.
ksJks.load(null, this._keyStorePass);
// Ajout du certificat dans le KeyStore Java.
ksJks.setKeyEntry(
alias,
ksP12.getKey(alias, this._certPass), // La clé du certificat.
this._keyStorePass,
ksP12.getCertificateChain(alias) // Le certificat.
);
aliases = ksJks.aliases();
while (aliases.hasMoreElements())
AppletAWS.print("\n" + (String) aliases.nextElement());
// Création d'une KeyManagerFactory.
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(ksJks, this._keyStorePass);
KeyManager[] keyManager = keyManagerFactory.getKeyManagers();
// TODO : créer un TrustManager sécurisé dans lequel on met nos données de certificats.
// Pour l'instant, afin de faire des tests, je fais confiance à tous les certificats.
TrustManager[] trustManager = new TrustManager[] {
new X509TrustManager() {
public boolean checkClientTrusted(java.security.cert.X509Certificate[] chain) {
return true;
}
public boolean isServerTrusted(java.security.cert.X509Certificate[] chain) {
return true;
}
public boolean isClientTrusted(java.security.cert.X509Certificate[] chain) {
return true;
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {}
}
};
// On crée notre contexte SSL.
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(keyManager, trustManager, null);
// Si il y a des proxys, on les ajoute à la connexion.
if (!proxysList.isEmpty()) {
for (Proxy proxy : proxysList) {
InetSocketAddress addr = (InetSocketAddress) proxy.address();
System.setProperty("http.proxyHost", addr.getHostName()); // L'adresse du proxy.
System.setProperty("http.proxyPort", Integer.toString(addr.getPort())); // Le port du proxy.
}
}
// On ajoute à l'HttpsURLConnection notre constexte SSL.
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
HttpsURLConnection.setFollowRedirects(true);
// Création et initialisation de la connexion HTTPS.
this._connection = (HttpsURLConnection) new URL(url).openConnection();
this._connection.setDoInput(true);
this._connection.setDoOutput(true);
String cookieHeader = this._connection.getHeaderField("set-cookie");
if (cookieHeader != null) {
String cuki = "";
int index = cookieHeader.indexOf(";");
if (index >= 0)
cuki = cookieHeader.substring(0, index);
this._connection.setRequestProperty("Cookie", cuki);
}
// this._connection.setRequestMethod("POST");
}
catch (Exception e) {
AppletAWS.err("Une erreur est survenue pendant la création de la connexion sécurisée : " + e.getMessage());
e.printStackTrace();
}
}
/**
* Crée le query à envoyer en POST.
* @param file le fichier à envoyer
* @param idClient l'ID du client
* @param idEtab l'ID de l'établissement
* @param md5File le MD5 du fichier à transférer
*/
public void setQuery(File file, String idClient, String idEtab, String md5File) {
final String encodage = "UTF-8";
try {
this._query = "fichier=" + URLEncoder.encode(new FileBody(file).getTransferEncoding(), encodage);
this._query += "&idClient=" + URLEncoder.encode(idClient, encodage);
this._query += "&idEtab=" + URLEncoder.encode(idEtab, encodage);
this._query += "&md5=" + URLEncoder.encode(md5File, encodage);
int queryLength = this._query.length();
AppletAWS.err("\nQuery : " + this._query);
AppletAWS.err("Longueur de la query : " + queryLength + "\n");
this._connection.setRequestProperty("Content-length", String.valueOf(queryLength));
this._connection.setRequestProperty("Content-Type", "application/x-www- form-urlencoded");
this._connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)");
}
catch (Exception e) {
AppletAWS.print("Une erreur est survenue lors de la création de la requête HTTPS : " + e.getMessage());
e.printStackTrace();
}
}
/**
* Envoi la requête.
*/
public void upload() {
try {
//connection.setRequestProperty("Accept-Language","it");
//connection.setRequestProperty("Accept", "application/cfm, image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, //*/*");
//connection.setRequestProperty("Accept-Encoding","gzip");
// open up the output stream of the connection
DataOutputStream output = new DataOutputStream(this._connection.getOutputStream());
// write out the data
output.writeBytes(this._query);
output.close();
int responseCode = this._connection.getResponseCode();
String responseMsg = this._connection.getResponseMessage();
AppletAWS.print("Resp code : " + responseCode);
AppletAWS.print("Resp message : " + responseMsg);
// get ready to read the response from the cgi script
DataInputStream input = new DataInputStream(this._connection.getInputStream());
// read in each character until end-of-stream is detected
AppletAWS.print("\nREPONSE :");
for (int c = input.read(); c != -1; c = input.read())
AppletAWS.print((char) c);
input.close();
}
catch (Exception e) {
AppletAWS.err("Une erreur est survenue pendant le transfert : " + e.getMessage());
e.printStackTrace();
}
}
/**
* Ferme la connexion.
*/
public void closeConnection() {
this._connection.disconnect();
}
} |
Partager