HTTP Request Creation J2SE - Yash-777/SteamingServlet GitHub Wiki
HttpURLConnection to POST XML/Text data
Class HttpURLConnection ectends URLConnection
String xmlStr = "...";
final HttpURLConnection httpURLConnection = (HttpURLConnection)new URL(s4).openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(true);
httpURLConnection.setRequestProperty("HTTP_ACCEPT_ENCODING", "gzip, deflate");
if (!xmlStr.equals("")) {
httpURLConnection.setRequestProperty("Content-type", "text/xml");
final DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.writeBytes(xmlStr);
dataOutputStream.close();
}
try {
final String streamContent = this.getStreamContent(httpURLConnection.getInputStream(), httpURLConnection.getContentEncoding());
if (httpURLConnection.getResponseCode() != 200) {
throw new Exception(httpURLConnection.getResponseMessage());
}
}
private String getStreamContent(final InputStream inputStream, final String encoding) throws IOException {
final byte[] pump = InputStreamPump.pump(inputStream, 0);
String s;
if (encoding == null) {
s = new String(pump);
} else {
s = new String(pump, encoding);
}
return s;
}
// ---------------------
public class InputStreamPump
{
// RETRYDELAY is in milliseconds
static public byte[] pump(InputStream inputStream, int retryDelay) throws IOException
{
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int status = 0;
while (status != -1)
{
int toRead = inputStream.available();
if (toRead == 0) toRead = 1; // mandatory to counter a bug when using an https
// connection: the inputstream provided in that case always return 0 when calling available()
// until you have forced to read at least 1 byte
byte[] buffer = null;
if (toRead == 1)
{
buffer = new byte[1];
int b = inputStream.read();
if (b == -1)
{
status = -1;
}
else
{
buffer[0] = (byte) b;
status = 1;
}
}
else
{
buffer = new byte[toRead];
status = inputStream.read(buffer);
}
if (status != -1)
{
byteBuffer.write(buffer, 0, status);
if (retryDelay > 0)
{
try
{
Thread.sleep(retryDelay);
}
catch (InterruptedException ie)
{
//ignore
}
}
}
}
return byteBuffer.toByteArray();
}
}
String authString = username + ":" + password;
String authMsg = "Basic " + Base64.encode(authString.getBytes());
InputStream sslCertificateStream = this.class.getResourceAsStream("C:/ssltest-cacerts.jks");
URL url = new URL(null, "https://www.programcreek.com/java-api-examples/?api=org.eclipse.jetty.server.HttpConnectionFactory");
HttpConnectionFactoryNew httpConnectionFactory = new HttpConnectionFactoryNew(httpsProxyHost, httpsProxyPort);
httpConnectionFactory.setClientCertificateStream(sslCertificateStream);
httpConnectionFactory.setCeritificateAlias("sslAlias");
HttpsURLConnection connection = (HttpsURLConnection) httpConnectionFactory.getHttpURLConnection(url);
connection.setReadTimeout(timeout);
connection.setConnectTimeout(timeout);
connection.setRequestProperty("Authorization", authMsg);
connection.setRequestMethod(httpMethod);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(true);
connection.setRequestProperty("HTTP_ACCEPT_ENCODING", "gzip, deflate");
String xmlRqst = "xml content";
connection.setRequestProperty("Content-type", "text/xml");
DataOutputStream printout = new DataOutputStream(connection.getOutputStream());
try {
printout.writeBytes(xmlRqst);
} finally {
printout.close();
}
int responseCode = 0;
String responseMessage = "Error";
InputStream is = connection.getInputStream();
String xmlRply = getStreamContent(is, connection.getContentEncoding());
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
public class HttpConnectionFactoryNew {
private Proxy proxy;
private String proxyHost;
private Integer proxyPort;
private String clientCertificatePassword;
private InputStream clientCertificateStream;
private String ceritificateAlias;
public HttpConnectionFactoryNew(){}
public HttpConnectionFactoryNew(String proxyHost, Integer proxyPort) {
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
}
private void initializeProxy() {
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
}
public Configuration getClientConfig() {
org.glassfish.jersey.client.ClientConfig config = new ClientConfig();
config.connectorProvider(new ApacheConnectorProvider());
//config.property(ClientProperties.PROXY_URI, "http://" + proxyHost + ":" + proxyPort);
// config.property(ClientProperties.PROXY_USERNAME, "user1");
// config.property(ClientProperties.PROXY_PASSWORD, "User1Pass");
return config;
}
public HttpURLConnection getHttpURLConnection(URL url) throws IOException {
HttpURLConnection httpURLConnection = null;
HttpsURLConnection httpsURLConnection = null;
if (proxyHost != null && proxyPort != null) {
initializeProxy();
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
} else { // No proxy
httpURLConnection = (HttpURLConnection) url.openConnection();
}
if (httpURLConnection instanceof HttpsURLConnection) {
try {
httpsURLConnection = getHttpsConnection(url);
} catch (Exception e) {
// EXception Http to Https
}
return httpsURLConnection;
} else {
return httpURLConnection;
}
}
private HttpsURLConnection getHttpsConnection(URL url) throws Exception {
HttpsURLConnection httpsURLConnection = null;
try {
if (proxy != null) {
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
} else {
httpsURLConnection = (HttpsURLConnection) url.openConnection();
}
httpsURLConnection.setHostnameVerifier(getHostnameVerifier());
SSLSocketFactory sslSocketFactory = null;
if (clientCertificatePassword != null) {
sslSocketFactory = this.getKeyStoreBasedSSLContext().getSocketFactory();
} else {
sslSocketFactory = this.getCertificateFactoryBasedSSLContext().getSocketFactory();
}
if (sslSocketFactory != null) {
httpsURLConnection.setSSLSocketFactory(sslSocketFactory);
} else {
throw new Exception("sslSocketFactory for sslcontext is null");
}
} catch (Exception e) {
e.printStacktrace();
}
return httpsURLConnection;
}
public HostnameVerifier getHostnameVerifier() {
return new HostnameVerifier() {
public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
return true;
}
};
}
public SSLContext getCertificateFactoryBasedSSLContext() throws Exception {
CertificateFactory certificateFactory;
X509Certificate x509Certificate;
TrustManagerFactory trustManagerFactory;
KeyStore keyStore;
SSLContext sslContext = null;
BufferedInputStream bufferedInputStream = null;
try {
bufferedInputStream = new BufferedInputStream(clientCertificateStream);
certificateFactory = CertificateFactory.getInstance("X.509");
x509Certificate = (X509Certificate) certificateFactory.generateCertificate(bufferedInputStream);
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null);
keyStore.setCertificateEntry(ceritificateAlias, x509Certificate);
trustManagerFactory.init(keyStore);
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
} catch (Exception e) {
throw new Exception(e);
} finally {
// Close bufferedInputStream, clientCertificateStream
}
return sslContext;
}
public SSLContext getKeyStoreBasedSSLContext() throws Exception {
SSLContext sslContext = null;
KeyStore clientStore = KeyStore.getInstance("PKCS12");
BufferedInputStream bufferedInputStream = new BufferedInputStream(clientCertificateStream);
try {
clientStore.load(bufferedInputStream, clientCertificatePassword.toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(clientStore, clientCertificatePassword.toCharArray());
KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
sslContext = SSLContext.getInstance("SSL");
sslContext.init(keyManagers, null, new SecureRandom());
} catch (Exception e) {
throw new Exception(e);
} finally {
// Close bufferedInputStream, clientCertificateStream
}
return sslContext;
}
}