We're trying to make secure http communication between client an server.
The server provided the certificates, we took them, install them and we start running, the point is to exchange an exact number of messages simultaneously between the client and server consecutively, the problem that's driving us crazy is that between the requests, at SSLHANDSHAKE we get randomly the exception javax.net.ssl.SSLException: Received fatal alert: unexpected_message exactly at ServerHello handshake phase, and i don't know how or why this is happening while it keeps working fine for 98% of the other requests.
it crashes at step 2.
Transporter.java : This is the class responsible for sending and receiving the data.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyStore;
import java.util.ResourceBundle;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
public class Transporter {
private static ResourceBundle resource = ResourceBundle.getBundle("resourece_00");
private static final String keystore = resource.getString("server_keystore");
private static final String truststore = resource.getString("server_truststore");
private static final String keypass = resource.getString("server_keystore_pwd");
private static final String trustpass = resource.getString("server_truststore_pwd");
// secure channel variables
private static SSLSocketFactory sslSocketFactory = null;
public Transporter() {
// setupSocketFactory();
}
static {
try {
String protocol = "TLS";
String type = "JKS";
String algorithm = KeyManagerFactory.getDefaultAlgorithm();
String trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
// create and initialize an SSLContext object
SSLContext sslContext = SSLContext.getInstance(protocol);
sslContext.init(getKeyManagers(type, algorithm), getTrustManagers(type, trustAlgorithm), null);
// obtain the SSLSocketFactory from the SSLContext
sslSocketFactory = sslContext.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
private static KeyStore getStore(String type, String filename, String pwd) throws Exception {
KeyStore ks = KeyStore.getInstance(type);
InputStream istream = null;
try {
File ksfile = new File(filename);
istream = new FileInputStream(ksfile);
ks.load(istream, pwd != null ? pwd.toCharArray() : null);
} finally {
if (istream != null) {
istream.close();
}
}
return ks;
}
private static KeyManager[] getKeyManagers(String type, String algorithm) throws Exception {
KeyStore ks = getStore(type, keystore, keypass);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(ks, keypass.toCharArray());
return kmf.getKeyManagers();
}
private static TrustManager[] getTrustManagers(String type, String algorithm) throws Exception {
KeyStore ts = getStore(type, truststore, trustpass);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
tmf.init(ts);
return tmf.getTrustManagers();
}
public String sendToVD(String msg, String urll, Long timeOut) {
byte[] bytes = msg.getBytes();
HttpsURLConnection sconn = null;
URL url = null;
OutputStream out = null;
BufferedReader read = null;
String recu = null;
try {
url = new URL(urll);
sconn = (HttpsURLConnection) url.openConnection();
sconn.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession sslSession) {
return true;
}
});
sconn.setSSLSocketFactory(sslSocketFactory);
// sconn.setReadTimeout((timeOut.intValue()) * 1000);// set timeout
sconn.setRequestMethod("POST");
sconn.addRequestProperty("Content-Length", "" + bytes.length);
sconn.setRequestProperty("Content-Type", "application/xml; charset=utf-8");
sconn.setDoOutput(true);
sconn.setDoInput(true);
// send POST data
// This is the crash location
out = sconn.getOutputStream();
// OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
out.write(bytes);
out.flush();
// logger.info("flush!!!!!!!!!!!!!");
// out.close();
read = new BufferedReader(new InputStreamReader(sconn.getInputStream()));
String query = null;
recu = read.readLine();
while ((query = read.readLine()) != null) {
recu += query;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// close all connections here
if (out != null)
out.close();
if (read != null)
read.close();
if (sconn != null)
sconn.disconnect();
} catch (Exception ce) {
}
}
return recu;
}
}
The function sendToVD() does the main work of the exchange between the client and the server.
At Client-End :
A web application with JSF managing the front layer, spring managing the beans life cycle, the communication entry to the client is assured by Servlets.
The client is deployed in a RedHat Linux machine, all TLS_VERSIONS are enbaled, JDK_8.
At Server-Side: i can't post the detailed information about the target URL for security measures, but it follows the following pattern https://ip:port/path, and it supports TLS_v1.2.
Hope you can help me out.
Related
We need to send a hash / digest of an XML file to a remote signing service.
The signing service returns a PKCS#7 response. This includes the signature and the short-lived-x509 certificate that was used.
Question: what is the easiest solution to apply the information from the PKCS#7 to the XML file so that it is correctly signed? I am looking for an example (Plain Java or Apache Santuario).
Update:
This is the code used for signing (xml-dsig) an XML with Apache Santuario given a local keystore:
package test.signer.signer;
import org.apache.commons.io.IOUtils;
import org.apache.xml.security.Init;
import org.apache.xml.security.c14n.Canonicalizer;
import org.apache.xml.security.signature.XMLSignature;
import org.apache.xml.security.transforms.Transforms;
import org.apache.xml.security.utils.Constants;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
/**
* from: https://stackoverflow.com/a/15911581/5658642
*/
public class CreateSignature
{
private static final String PRIVATE_KEY_ALIAS = "sgw-sign-client-keystore";
private static final String PRIVATE_KEY_PASS = "password";
private static final String KEY_STORE_PASS = "";
private static final String KEY_STORE_TYPE = "JKS";
public static void main(String... unused) throws Exception
{
final InputStream fileInputStream = Files.newInputStream(Paths.get("unsigned_DEV.xml"));
try
{
output(signFile(fileInputStream, new File("sgw-sign-client-keystore.jks")), "signed-test.xml");
} finally
{
IOUtils.closeQuietly(fileInputStream);
}
}
public static ByteArrayOutputStream signFile(InputStream xmlFile, File privateKeyFile) throws Exception
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xmlFile);
Init.init();
final KeyStore keyStore = loadKeyStore(privateKeyFile);
final XMLSignature sig = new XMLSignature(doc, null, XMLSignature.ALGO_ID_SIGNATURE_RSA);
doc.getDocumentElement().appendChild(sig.getElement());
final Transforms transforms = new Transforms(doc);
transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
// TODO replace with external signature
final Key privateKey = keyStore.getKey(PRIVATE_KEY_ALIAS, PRIVATE_KEY_PASS.toCharArray());
final X509Certificate cert = (X509Certificate) keyStore.getCertificate(PRIVATE_KEY_ALIAS);
sig.addKeyInfo(cert);
sig.addKeyInfo(cert.getPublicKey());
sig.sign(privateKey);
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(doc));
return outputStream;
}
private static KeyStore loadKeyStore(File privateKeyFile) throws Exception
{
final InputStream fileInputStream = Files.newInputStream(privateKeyFile.toPath());
try
{
final KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
keyStore.load(fileInputStream, null);
return keyStore;
} finally
{
IOUtils.closeQuietly(fileInputStream);
}
}
private static void output(ByteArrayOutputStream signedOutputStream, String fileName) throws IOException
{
final OutputStream fileOutputStream = Files.newOutputStream(Paths.get(fileName));
try
{
fileOutputStream.write(signedOutputStream.toByteArray());
fileOutputStream.flush();
} finally
{
IOUtils.closeQuietly(fileOutputStream);
}
}
}
This works so far. I now must replace the local keystore with a "remote keystore". The remote signing service takes a digest / hash and signs it. The response is a valid PKCS#7, which contains the certificate and the signature.
I am able to extract both with the following code (based on CMSSignedData from BouncyCastle):
String hashB64 = Base64.getEncoder().encodeToString(digest);
byte[] pkcs7Signature = remoteServiceClientService.sign(hashB64);
CMSSignedData cms = null;
try
{
cms = new CMSSignedData(pkcs7Signature);
SignerInformationStore signers = cms.getSignerInfos();
Collection<SignerInformation> c = signers.getSigners();
for (SignerInformation signer : c) {
// this collection will contain the signer certificate, if present
Collection<X509CertificateHolder> signerCol = cms.getCertificates().getMatches(signer.getSID());
SIG_CERT = new JcaX509CertificateConverter().getCertificate(signerCol.stream().findFirst().get());
}
List<byte[]> signatures = cms.getSignerInfos().getSigners().stream().map(SignerInformation::getSignature)
.collect(Collectors.toList());
byte[] pkcs1Signature = signatures.get(0);
SOPLogger.log("Plain Signature", pkcs1Signature);
return pkcs1Signature;
} catch (CMSException e)
{
throw new RuntimeException(e);
} catch (CertificateException e)
{
throw new RuntimeException(e);
}
I have no idea how to apply the extracted information instead of using a local keystore and are happy to try any hints.
I have a simple ServerEndpoint running on WildFly 10, which is configured as wss with mutual TLS, so client certificate required. I have no problems in connecting to endpoint, so the mutual authentication is correctly done, but I can't access client certificate in onOpen method. I am trying to do it using getUserPrincipal(), I'm always getting null.
I need to get client certificate for authorization purposes.
import java.io.IOException;
import java.security.Principal;
import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint(value = "/test", configurator = GetHttpSessionConfigurator.class)
public class TestWebSocketEndPoint {
private Session wsSession;
private HttpSession httpSession;
#OnOpen
public void onOpen(Session session, EndpointConfig config){
this.wsSession = session;
this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
Principal userPrincipal = session.getUserPrincipal();
System.out.println(session.getId() + " has opened a connection");
try {
session.getBasicRemote().sendText("Connection Established");
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* When a user sends a message to the server, this method will intercept the message
* and allow us to react to it. For now the message is read as a String.
*/
#OnMessage
public void onMessage(String message, Session session){
System.out.println("Message from " + session.getId() + ": " + message);
try {
session.getBasicRemote().sendText(message);
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* The user closes the connection.
*
* Note: you can't send messages to the client from this method
*/
#OnClose
public void onClose(Session session){
System.out.println("Session " +session.getId()+" has ended");
}
}
GetHttpSessionConfigurator:
import java.security.Principal;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator {
#Override
public void modifyHandshake(ServerEndpointConfig config,
HandshakeRequest request,
HandshakeResponse response)
{
HttpSession httpSession = (HttpSession)request.getHttpSession();
Map<String, List<String>> map = request.getParameterMap();
Principal principal = request.getUserPrincipal();
config.getUserProperties().put(HttpSession.class.getName(),httpSession);
}
}
RequestListener:
import java.security.Principal;
import java.security.cert.X509Certificate;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
#WebListener
public class RequestListener implements ServletRequestListener {
public void requestDestroyed(ServletRequestEvent sre) {
// TODO Auto-generated method stub
}
public void requestInitialized(ServletRequestEvent sre) {
((HttpServletRequest) sre.getServletRequest()).getSession();
Principal p = ((HttpServletRequest) sre.getServletRequest()).getUserPrincipal();
boolean secure = ((HttpServletRequest) sre.getServletRequest()).isSecure();
String authType = ((HttpServletRequest) sre.getServletRequest()).getAuthType();
X509Certificate[] certs = (X509Certificate[]) ((HttpServletRequest) sre.getServletRequest()).getAttribute("javax.servlet.request.X509Certificate");
}
}
The websocket client is a standalone application using TooTallNate/java-websocket and connecting securely:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.Enumeration;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.java_websocket.WebSocketImpl;
public class TestClient {
private static final Log log = LogFactory.getLog(TestClient.class);
public static void main(String[] args) throws URISyntaxException {
WebSocketImpl.DEBUG = true;
WSRAClient wsRaClient = new WSRAClient(new URI("wss://localhost:8443/TestWebSocket-0.0.1-SNAPSHOT/test"));
String keystoreFile = "keystore.p12";
String keystorePassword = "keystore";
String truststoreFile = "truststore.jks";
String truststorePassword = "truststore";
try {
SSLContext ssl = SSLContext.getInstance("TLSv1.2");
log.info("Configuring SSL keystore");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
log.debug("Loading keystore");
store.load(new FileInputStream(keystoreFile), keystorePassword.toCharArray());
log.debug("Number of keystore certificates: " + store.size());
Enumeration<String> enumeration = store.aliases();
while(enumeration.hasMoreElements()) {
String alias = enumeration.nextElement();
log.debug("alias name: " + alias);
Certificate certificate = store.getCertificate(alias);
log.debug(certificate.toString());
}
kmf.init(store, keystorePassword.toCharArray());
KeyManager[] keyManagers = new KeyManager[1];
keyManagers = kmf.getKeyManagers();
log.info("Configuring SSL truststore");
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore truststore = KeyStore.getInstance(KeyStore.getDefaultType());
log.debug("Loading truststore");
truststore.load(new FileInputStream(truststoreFile), truststorePassword.toCharArray());
log.debug("Number of truststore certificates: " + truststore.size());
enumeration = truststore.aliases();
while(enumeration.hasMoreElements()) {
String alias = (String)enumeration.nextElement();
log.debug("alias name: " + alias);
Certificate certificate = truststore.getCertificate(alias);
log.debug(certificate.toString());
}
tmf.init(truststore);
TrustManager[] trustManagers = tmf.getTrustManagers();
ssl.init(keyManagers, trustManagers, new SecureRandom());
SSLSocketFactory factory = ssl.getSocketFactory();// (SSLSocketFactory) SSLSocketFactory.getDefault();
wsRaClient.setSocket(factory.createSocket());
wsRaClient.connectBlocking();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while ( true ) {
String line = reader.readLine();
if(line.equals("close")) {
wsRaClient.close();
} else {
wsRaClient.send(line);
}
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (KeyStoreException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (CertificateException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (KeyManagementException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
} catch (InterruptedException e) {
e.printStackTrace();
log.error(e);
System.exit(0);
}
}
}
See : Accessing HttpServletRequest properties within a WebSocket #ServerEndpoint
Create servlet filter on URL pattern matching websocket handshake request.
In filter, get request attribute of interest and put it in session before continuing chain.
Finally get it from the session which is in turn just available via handshake request
I want to download a response of the below wget command in windows:
wget --no-check-certificate --post-data 'login=xxx&password=yyy' https://AAA.BBB.CCC.DDD:1234/login -O -
This command works fine in linux, but it's not working in windows. I know if I install wget on windows, then it will work. I want to run it without installing it. I want the option for above wget command for above specified url to achieve the target.
So far i have tried the below snippet of code But it only returns html info (source code) of the page without going to the homepage using username and password.
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.codec.binary.Base64;
public class ConnectToUrlUsingBasicAuthentication
{
static
{
disableSslVerification();
}
private static void disableSslVerification()
{
try
{
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session)
{
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (KeyManagementException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
try
{
String webPage = "https://AAA.BBB.CCC.DDD:1234/login";
String name = "xxx";
String password = "yyy";
String authString = name + ":" + password;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
System.out.println("Base64 encoded auth string: " + authStringEnc);
URL url = new URL(webPage);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
javax.net.ssl.HostnameVerifier myHv = new javax.net.ssl.HostnameVerifier(){
public boolean verify(String
hostName,javax.net.ssl.SSLSession session) { return true; }
};
((HttpsURLConnection) urlConnection).setHostnameVerifier(myHv); urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0)
{
sb.append(charArray, 0, numCharsRead);
}
String result = sb.toString();
System.out.println("*** BEGIN ***");
System.out.println(result);
System.out.println("*** END ***");
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
I am beginner to android.
I am working on client side code I have to read images store on server and display it in imageview.
I have refer some stackoverflow question but not able to succeed.
I did simple plain java program with HttpsURLConnection class I got the some binary response from server for image, thats ok with plain java code.
But when I tried the same thing in android with little bit change in code, I got the Exception:
01-29 18:39:28.199: WARN/System.err(2045): java.io.IOException: SSL handshake failure: I/O error during system call, Unknown error: 0
01-29 18:39:28.249: WARN/System.err(2045): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.nativeconnect(Native Method)
01-29 18:39:28.249: WARN/System.err(2045): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:316)
01-29 18:39:28.249: WARN/System.err(2045): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.getSecureSocket(HttpConnection.java:168)
01-29 18:39:28.249: WARN/System.err(2045): at org.apache.harmony.luni.internal.net.www.protocol.https.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:399)
This is my public URL of sample image:
https://s3-ap-southeast-1.amazonaws.com/edt-demo-app/app-images/Mobile.jpg
The code which works fine for me in plain java is as follows:
package com.psl.dao;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
mport javax.net.ssl.HttpsURLConnection;
public class HttpsClient{
public static void main(String[] args)
{
String url = "https://s3-ap-southeast-1.amazonaws.com/edt-demo-app/app-images/Mobile.jpg";
try {
new HttpsClient().print(url);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void print(String url)throws Exception
{
String httpsURL = url;
URL myurl = new URL(httpsURL);
System.setProperty("https.proxyHost", "puproxy.company.co.in");
System.setProperty("https.proxyPort", "8080");
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
System.out.println(con.toString());
InputStream ins = con.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
String inputLine;
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine);
}
in.close();
}
}
Then I have refer some android tutorial and tried following code in my android app:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class TestSSL {
public static void main(String[] args) throws Exception {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
// Install the all-trusting trust manager
final SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
System.setProperty("https.proxyHost", "puproxy.company.co.in");
System.setProperty("https.proxyPort", "8080");
URL url = new URL("https://s3-ap-southeast-1.amazonaws.com/edt-demo-app/app-images/Mobile.jpg");
URLConnection con = url.openConnection();
final Reader reader = new InputStreamReader(con.getInputStream());
final BufferedReader br = new BufferedReader(reader);
String line = "";
while ((line = br.readLine()) != null) {
Log.d("tag",line+"");
}
br.close();
} // End of main
} // End of the class //
But I got exception as above said:
01-29 18:39:28.199: WARN/System.err(2045): java.io.IOException: SSL handshake failure: I/O error during system call, Unknown error: 0
Any other code that works fine with Apache HttpClient or Async HttP client library by using Asynynchronusly loading of image would welcome.
Also I dont know how to do proxy setting in android. so please do it for me with respective parameter
I have tried follwing tutorial but my image is not displayed.
http://javatechig.com/android/download-image-using-asynctask-in-android
The above tutorial works fine for Http URL but not for Https
I want code like in above tutorial that works fine for HTTPS URL For time being consider server certificate is not important for me.
Please try this code
MainActivity
package com.example.androidhttpsdemo;
/*
*
* MainActivity.java
* #author Santosh Shinde
* Date: 30/01/2015 12:28:16 PM
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.net.ssl.HttpsURLConnection;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends Activity {
//public static final String URL ="https://googledrive.com/host/0B_DiX4MiMa3HTHdiYVRmUHBMcW8/image1.jpg";
public static final String URL="https://s3-ap-southeast-1.amazonaws.com/edt-demo-app/app-images/Mobile.jpg";
ImageView imageView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.ImageView1);
// Create an object for subclass of AsyncTask
GetXMLTask task = new GetXMLTask();
// Execute the task
task.execute(new String[] { URL });
}
private class GetXMLTask extends AsyncTask {
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
System.out.println("finished");
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpsURLConnection httpConnection = (HttpsURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpsURLConnection.HTTP_OK ||
httpConnection.getResponseCode() == HttpsURLConnection.HTTP_NOT_MODIFIED ) {
stream = httpConnection.getInputStream();
} else { // just in case..
//log.d("Surprize HTTP status was: " ,httpConnection.getResponseCode());
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
}
try this code...
try
{
InputStream imageURL = new URL (url).openStream();
bitmap = BitmapFactory.decodeStream(imageURL);
}
catch (Exception e)
{
e.printStackTrace();
}
Best solution is
Android-Universal-Image-Loader, it is very simple to use.
You can simply set dataBinding in your build.gradle to true add Glide Lib to load Images nicely
android {
compileSdkVersion 25
buildToolsVersion '25.0.3'
dataBinding {
enabled = true
}
...
}
And create a BindingAdapter, this will overwrite the current method(in this case
android:src="...") and load the image.
#BindingAdapter("android:src")
public static void setImageUrl(ImageView imageView, String url) {
Context context = imageView.getContext();
Glide.with(context).load(url).into(imageView);
}
Now you can just simple pass an url in the xml and it will load the Image, this method can be placed anywhere in the code.
<ImageView
android:id="#+id/status_avatar"
android:layout_width="64dp"
android:layout_height="64dp"
android:src="http://knightwise.com/wp-content/uploads/2014/02/android-apple-wallpaper.jpg"/>
Iam unable to post the data to the server, getting error as . But it is working fine in curl script.
Error reading URL
java.io.IOException: Server returned HTTP response code: 415 for URL: https://8.7.177.4/api/domains/amj.nms.mixnetworks.net/subscribers/9001?do_not_disturb=no
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at CurlAuthentication.authenticatePostUrl(CurlAuthentication.java:109)
at CurlAuthentication.main(CurlAuthentication.java:134)
Error reading URL
Below is the code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
public class CurlAuthentication {
public void authenticatePostUrl() {
HostnameVerifier hv = new HostnameVerifier() {
#Override
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName
+ " vs. " + session.getPeerHost());
return true;
}
};
// Now you are telling the JRE to trust any https server.
// If you know the URL that you are connecting to then this should
// not be a problem
try {
trustAllHttpsCertificates();
} catch (Exception e) {
System.out.println("Trustall" + e.getStackTrace());
}
HttpsURLConnection.setDefaultHostnameVerifier(hv);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
URL url = new URL("www.stackoverflow.com");
String credentials = "user" + ":" + "password";
String encoding = Base64Converter.encode(credentials.getBytes("UTF-8"));
HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
uc.setDoInput(true);
uc.setDoOutput(true);
uc.setRequestProperty("Authorization", String.format("Basic %s", encoding));
uc.setRequestMethod("POST");
uc.setRequestProperty("Content-Type", "application/xml");
uc.setRequestProperty("Accept", "application/xml");
uc.getInputStream();
System.out.println(uc.getContentType());
InputStream content = (InputStream) uc.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(
content));
String line;
while ((line = in.readLine()) != null) {
pw.println(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
pw.println("Invalid URL");
} catch (IOException e) {
e.printStackTrace();
pw.println("Error reading URL");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(sw.toString());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CurlAuthentication au = new CurlAuthentication();
au.authenticatePostUrl();
}
// Just add these two functions in your program
public static class TempTrustedManager implements
javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}
private static void trustAllHttpsCertificates() throws Exception {
// Create a trust manager that does not validate certificate chains:
javax.net.ssl.TrustManager[] trustAllCerts =
new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new TempTrustedManager();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc =
javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(
sc.getSocketFactory());
}
}
Do iam doing anything wrong from the above code?
DO i need to use curl script to post the data?
Well, as Error 415 is already stating:
415 Unsupported Media Type
The request entity has a media type which the server or resource does not support. For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.
Without knowing the specifications of what the server is expecting of you to send him, it's hard to tell what you are missing. It though seems as if you only want to receive data from the server and not send him anything.
By setting uc.setRequestProperty("Content-Type", "application/xml"); you tell the server that you hand him over some XML data (which you don't) and he probably also wouldn't expect this, so he's giving you that error.
As your sending some urlencoded data in your POST data, try setting this to:
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");