I am trying to use a cert that I downloaded from goDaddy that is hosting my server. I want to connect to it via my android app using an https connection. This connection needs to be authenticated as well. I got it all working with http but when I try to use the local certificate it just fatal crashes saying that I am trying to cast an httpUrlConnection to an HttpsUrlConnection.
Caused by: java.lang.ClassCastException: com.android.okhttp.internal.huc.HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection
I don't know what I am doing wrong there is no httpurlConneciton in the code at all and I don't cast anything to https either. Any help with this will be appreciated.
Here is my HttpsGet Client.
public class MyHttpsGet extends AsyncTask<String, Void, String> {
Context context;
int cert;
boolean allowHost;
private String username;
private String password;
//this is used if you need a password and username
//mainly for logins to a webserver
public MyHttpsGet(String username, String password, Context context, int cert)
{
this.context = context;
this.cert = cert;
this.allowHost = allowHost;
this.username = username;
this.password = password;
}
//used for image downloading
public MyHttpsGet(){}
#Override
protected String doInBackground(String... params) {
String url = params[0];
return httpsDownloadData(url, context, cert);
}
public String httpsDownloadData (String urlString, Context context, int certRawResId)
{
String respone = null;
try {
// build key store with ca certificate
KeyStore keyStore = buildKeyStore(context, certRawResId);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
// Create a connection from url
URL url = new URL(urlString);
if (username != null) {
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
}
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
int statusCode = urlConnection.getResponseCode();
Log.d("Status code: ", Integer.toString(statusCode));
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
respone = streamToString(inputStream);
inputStream.close();
}
}catch (IOException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
Log.d("MyHttps Respones: ", respone);
return respone;
}
private static KeyStore buildKeyStore(Context context, int certRawResId) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
// init a default key store
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
// read and add certificate authority
Certificate cert = readCert(context, certRawResId);
keyStore.setCertificateEntry("ca", cert);
return keyStore;
}
private static Certificate readCert(Context context, int certResourceId) throws CertificateException, IOException {
// read certificate resource
InputStream caInput = context.getResources().openRawResource(certResourceId);
Certificate ca;
try {
// generate a certificate
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ca = cf.generateCertificate(caInput);
} finally {
caInput.close();
}
return ca;
}
//this is used for downloading strings from an http or https connection
private String streamToString(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
And here is how I am using it /calling it.
MyHttpsGet task = new MyHttpsGet(username, password,myContext, R.raw.gdroot_g2);
try {
myJson = task.execute(myUrl).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
new runningMan().execute();
This was caused not by my code but by the missing s in a https//www.godsjasdifdsaidsf.com
Related
I am trying to connect Azure SQL Database using Android Application, While connecting to the Azure SQL database, I am getting SSL Handshake aborted issue. I am using the latest android studio 4.1.2 version and the Android Version was Lollipop 5.0. and also I added a TLS certificate to the application.
Any idea how to fix it ??
Here is my java code :
public static void SetUpHttpsConnection(String urlString) {
String response = null;
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
System.out.println("Loading Certificate from Assets folder ....");
InputStream caInput = new BufferedInputStream(MainActivity.context.getAssets().open("ca-bundle.crt"));
X509Certificate caCertificate = (X509Certificate) cf.generateCertificate(caInput);
Certificate ca = cf.generateCertificate(caInput);
System.out.println("generate certificate .............");
System.out.println("ca : " + (caCertificate).getSubjectDN());
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", caCertificate);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
System.out.println(" Trust Manager Factory ------ ");
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context1 = SSLContext.getInstance("TLS");
//SSLContext context1 = SSLContext.getInstance("TLSv1.2");
System.out.println(" ------------------------------- ");
//context1.init(null, tmf.getTrustManagers(), null);
System.out.println("SSL context ---- :" + context1);
context1.init(null, new X509TrustManager[]{new X509TrustManager(){
#SuppressLint("TrustAllX509TrustManager")
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
#SuppressLint("TrustAllX509TrustManager")
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(
context1.getSocketFactory());
System.out.println("Trust Certificates ----- ");
// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = new URL(urlString);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
if (urlConnection instanceof HttpsURLConnection) {
HttpsURLConnection httpsConn = (HttpsURLConnection) urlConnection;
httpsConn.setSSLSocketFactory(SSLCertificateSocketFactory.getInsecure(0,null));
httpsConn.setHostnameVerifier(new AllowAllHostnameVerifier());
httpsConn.setRequestProperty("Connection", "Keep-Alive");
httpsConn.setRequestProperty("Charset", "UTF-8");
}
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(2500);
urlConnection.setReadTimeout(3500);
urlConnection.setRequestProperty("Content-Type", "application/json");
int statuscode = urlConnection.getResponseCode();
Log.d("Status code :", Integer.toString(statuscode));
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
response = streamToString(inputStream);
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String readStream(InputStream is) throws IOException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("US-ASCII")));
StringBuilder total = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
total.append(line);
}
if (reader != null) {
reader.close();
}
return total.toString();
}
private static String streamToString(InputStream inputStream) throws IOException {
StringBuffer sb = new StringBuffer();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = rd.readLine())!= null) {
sb.append(line);
}
return sb.toString();
}
#SuppressLint("StaticFieldLeak")
private class Azure_Connection extends AsyncTask<String, Void, Iterable<Test>> {
String res = "";
private String rowKey;
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this, "Please wait...", Toast.LENGTH_SHORT)
.show();
}
protected Iterable<Test> doInBackground(String... arg0) {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
System.out.println("Reading JDBC Driver");
String UserName = "username#iwavesqlserver";
String Passwrd = "*******";
String ConnectionString = "jdbc:jtds:sqlserver://iwavesqlserver.database.windows.net:1433/iwave_db_1;loginTimeout=300;ssl=require;" +
"integratedSecurity=true;encrypt=false;TrustServerCertificate=true;hostNameInCertificate=*.database.windows.net;";
System.out.println(" .......... Connecting to the SQL Database .......... ");
String urlString = "https://portal.azure.com/#home";
SetUpHttpsConnection(urlString);
try {
Connection connection = DriverManager.getConnection(ConnectionString, UserName, Passwrd);
if (connection != null) {
System.out.println("Database connection success");
}
Statement stmt = Objects.requireNonNull(connection).createStatement();
ResultSet resultSet = stmt.executeQuery("SELECT * FROM test");
log.info("Database Connection test : " + connection);
} catch (SQLException e) {
e.printStackTrace();
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
}
Error message :
I/System.out: Connection Exception : java.sql.SQLException: Network error IOException: SSL handshake aborted: ssl=0xebc432c8: I/O error during system call, Broken pipe
W/System.err: java.sql.SQLException: Network error IOException: SSL handshake aborted: ssl=0xebc432c8: I/O error during system call, Broken pipe
W/System.err: at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:436)
W/System.err: at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(DriverManager.java:569)
W/System.err: at java.sql.DriverManager.getConnection(DriverManager.java:219)
at com.iwavesys.cloudazure.MainActivity$Azure_Connection.doInBackground(MainActivity.java:381)
at com.iwavesys.cloudazure.MainActivity$Azure_Connection.doInBackground(MainActivity.java:316)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
W/System.err: Caused by: javax.net.ssl.SSLHandshakeException: SSL handshake aborted: ssl=0xebc432c8: I/O error during system call, Broken pipe
at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
I am not sure this is the correct way to add certificates and get a connection to the Azure SQL database. please anyone help me to solve this issue.
Thank you.
I am trying to connect my android app to a url belonging to a private company in order to retrieve and send information. When I do so however I receive an error Trust anchor for certification path not found, the ssl certificate for the url is valid though, I did research and I used the following code I used to trust the certificate in a class Http TrustManager
public class HttpsTrustManager {
public void trust() throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = new BufferedInputStream(new FileInputStream("load-der.crt"));
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
SSLContext context = null;
try {
context = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
context.init(null, tmf.getTrustManagers(), null);
} catch (KeyManagementException e) {
e.printStackTrace();
}
// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = new URL("https://systems.syspearl.com/api");
HttpsURLConnection urlConnection =
(HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
InputStream in = urlConnection.getInputStream();
IOUtils.copyStream(in,out);
}
And this is how I call it in the main activity
new HttpsTrusrtManger().trust();
This doesn't work however. Please render necessary help
I am trying to access my server using two of the goDaddy certificates that are listed under my endpoint. The three certs in the stack are My cert > Go Daddy Secure Certificate Authority -G2 > Go Daddy Root Certificate Authority - G2. I downloaded both the secure and root certs from the Go Daddy Repository and now have added both to my android app raw resource folder. Even with both in there it still gives me this error
javax.net.ssl.SSLPeerUnverifiedException: Hostname not verified:
I don't know what i should do next. I tried a lot of combinations so I think i need a different way of doing this.
Here is what I have so far;
My HttpsClient code;
public class MyHttpsGet extends AsyncTask<String, Void, String> {
Context context;
int cert;
int interCert;
boolean allowHost;
private String username;
private String password;
//this is used if you need a password and username
//mainly for logins to a webserver
public MyHttpsGet(String username, String password, Context context, int cert, int intermedCert)
{
this.context = context;
this.cert = cert;
this.interCert = intermedCert;
this.username = username;
this.password = password;
}
//used for image downloading
public MyHttpsGet(){}
#Override
protected String doInBackground(String... params) {
String url = params[0];
return httpsDownloadData(url, context, cert, interCert);
}
public String httpsDownloadData (String urlString, Context context, int certRawResId, int certIntermedResId)
{
String respone = null;
try {
// build key store with ca certificate
KeyStore keyStore = buildKeyStore(context, certRawResId, certIntermedResId);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
// Create a connection from url
URL url = new URL(urlString);
if (username != null) {
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
}
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
int statusCode = urlConnection.getResponseCode();
Log.d("Status code: ", Integer.toString(statusCode));
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
respone = streamToString(inputStream);
inputStream.close();
}
}catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
Log.d("MyHttps Respones: ", respone);
return respone;
}
private static KeyStore buildKeyStore(Context context, int certRawResId, int interCert){
// init a default key store
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
// read and add certificate authority
Certificate cert2 = readCert(context, interCert);
Certificate cert = readCert(context, certRawResId);
keyStore.setCertificateEntry("ca" , cert2);
keyStore.setCertificateEntry("ca", cert);
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return keyStore;
}
private static Certificate readCert(Context context, int certResourceId) throws IOException {
// read certificate resource
InputStream caInput = context.getResources().openRawResource(certResourceId);
Certificate ca = null;
try {
// generate a certificate
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ca = cf.generateCertificate(caInput);
} catch (CertificateException e) {
e.printStackTrace();
} finally {
caInput.close();
}
return ca;
}
//this is used for downloading strings from an http or https connection
private String streamToString(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
}
And here is how I call it/use it:
MyHttpsGet task = new MyHttpsGet(username, password,myContext, R.raw.gdroot_g2, R.raw.gdintermed);
try {
myJson = task.execute(myUrl).get();
Log.d("Json: " , myJson);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
new runningMan().execute();
Thank you for any help with this.
Here is a picture of my Cert Chain
The error message says apivitacrm.elasticbeanstalk.com, but you then black out the wildcard name in your certificate. Why?
Well, regardless of what it is, it looks like it starts with an a, so it is definitely not a *.elasticbeanstalk.com wildcard certificate.
That means that the error message is correct. The certificate does not belong to the domain name given.
Even if it is a *.apivitacrm.elasticbeanstalk.com wildcard (blackout doesn't seem wide enough for that, though), it still wouldn't match apivitacrm.elasticbeanstalk.com, since it only matches subdomains.
Dear SO Community of Awesomeness,
I'm building a secure app that deals with sensitive information. The app communicates with my own RESTful API over SSL. I don't want to limit the app to the specific certificate I was issued, but rather to trust only certificates issued by my provider, e.g. Comodo. That way I can extend and reissue the certificate without having to release an app update.
I found a great resource for getting this done here but Android 6 deprecated HttpClient and switched to HttpsURLConnection. Google has their own approach posted here. On implementation, however, I noticed that instead of throwing a "not trusted" exception for a different certificate, it just forced the usage of the local CA cert which is not the behavior I intended.
Does anyone have a reference for trusting only a specific CA using HttpsURLConnection?
OK I solved it, figured I would post the solution in case anyone else hits the same problem. Here is the code to use to get a JSON file using HttpsUrlConnection:
(...)
public static class GetJsonTask extends AsyncTask<Void, Integer, AsyncResponse> {
protected String jsonData;
protected IGetJsonListener listener;
protected Context context = null;
protected String strUrl;
public GetJsonTask(Context c, IGetJsonListener l, String strUrl) {
super();
listener = l;
context = c;
this.strUrl = strUrl;
}
#Override
protected AsyncResponse doInBackground(Void... Void) {
JsonObject jsonObjectResult = new JsonObject();
APIStatus status;
if (isConnected(context)) {
HttpsURLConnection httpsURLConnection=null;
try {
//THIS IS KEY: context contains only our CA cert
SSLContext sslContext = getSSLContext(context);
if (sslContext != null) {
//for HTTP BASIC AUTH if your server implements this
//String encoded = Base64.encodeToString(
// ("your_user_name" + ":" + "your_pwd").getBytes(),
// Base64.DEFAULT);
URL url = new URL(strUrl);
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestMethod("GET");
httpsURLConnection.setRequestProperty("Content-length", "0");
httpsURLConnection.setUseCaches(false);
httpsURLConnection.setAllowUserInteraction(false);
//FOR HTTP BASIC AUTH
//httpsURLConnection.setRequestProperty("Authorization", "Basic " + encoded);
//THIS IS KEY: Set connection to use custom socket factory
httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());
//httpsURLConnection.setConnectTimeout(timeout);
//httpsURLConnection.setReadTimeout(timeout);
httpsURLConnection.connect();
status = getStatusFromCode(httpsURLConnection.getResponseCode());
listener.getJsonShowProgress(90);
if (status == APIStatus.OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
bufferedReader.close();
JsonParser parser = new JsonParser();
String s = stringBuilder.toString();
jsonObjectResult = (JsonObject) parser.parse(s);
}
} else
status = APIStatus.AUTH_ERROR;
listener.getJsonShowProgress(99);
//THIS IS KEY: this exception is thrown if the certificate
//is signed by a CA that is not our CA
} catch (SSLHandshakeException e) {
status = APIStatus.AUTH_ERROR;
//React to what is probably a man-in-the-middle attack
} catch (IOException e) {
status = APIStatus.NET_ERROR;
} catch (JsonParseException e) {
status = APIStatus.JSON_ERROR;
} catch (Exception e) {
status = APIStatus.UNKNOWN_ERROR;
} finally {
if (httpsURLConnection != null)
httpsURLConnection.disconnect();
}
} else {
status = APIStatus.NET_ERROR;
}
// if not successful issue another call for the next hour.
AsyncResponse response = new AsyncResponse();
response.jsonData = jsonObjectResult;
response.opStatus = status;
return response;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (listener != null)
listener.getJsonStartProgress();
}
#Override
protected void onProgressUpdate(Integer... progress) {
listener.getJsonShowProgress(progress[0]);
}
#Override
protected void onPostExecute(AsyncResponse result) {
listener.getJsonFinished(result.jsonData, result.opStatus);
}
public interface IGetJsonListener {
void getJsonStartProgress();
void getJsonShowProgress(int percent);
void getJsonFinished(JsonObject resJson, APIStatus status);
}
}
private static SSLContext getSSLContext(Context context){
//Mostly taken from the Google code link in the question.
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
AssetManager am = context.getAssets();
//THIS IS KEY: Your CA's cert stored in /assets/
InputStream caInput = new BufferedInputStream(am.open("RootCA.crt"));
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
//System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
return sslContext;
} catch (Exception e){
return null;
}
}
public enum APIStatus {
OK("OK.", 200), //all went well
JSON_ERROR("Error parsing response.", 1),
NET_ERROR("Network error.", 2), //we couldn't reach the server
UNKNOWN_ERROR("Unknown error.", 3), //some sh*t went down
AUTH_ERROR("Authentication error.", 401), //credentials where wrong
SERVER_ERROR("Internal server error.", 500), //server code crashed
TIMEOUT("Operation timed out.", 408); //network too slow or server overloaded
private String stringValue;
private int intValue;
private APIStatus(String toString, int value) {
stringValue = toString;
intValue = value;
}
#Override
public String toString() {
return stringValue;
}
}
private static APIStatus getStatusFromCode(int code) {
if (code==200 || code==201) {
return APIStatus.OK;
}else if (code == 401) {
return APIStatus.AUTH_ERROR;
} else if (code == 500) {
return APIStatus.SERVER_ERROR;
} else if (code == 408) {
return APIStatus.TIMEOUT;
} else {
return APIStatus.UNKNOWN_ERROR;
}
}
private static class AsyncResponse {
public APIStatus opStatus;
public JsonObject jsonData;
}
(...)
Usage is fairly straightforward:
public class MyClass implements IGetJsonListener {
(...)
new GetJsonTask(context, this, "https://your.url.com/").execute();
#Override
public void getJsonFinished(JsonObject resJson, APIStatus status) {
//Handle JSON content from web here
(...)
}
(...)
}
I'd love to hear any improvements you have.
I have a string that I'm passing around which represents an X509Certificate generated by:
String strMessage =
Base64.encodeToString(chain[0].getEncoded(), android.util.Base64.NO_WRAP);
This is so the user can view a certificate and possibly accept it. If they do decide to accept it I need to create a Keystore object to which to add to my custom SSL factory (as here:)
private SSLSocketFactory newSslSocketFactory(boolean trustCert, String cert) {
try {
KeyStore trusted = KeyStore.getInstance("BKS");
if(trustCert) {
String cert_begin = "-----BEGIN CERTIFICATE-----\n";
String end_cert = "-----END CERTIFICATE-----";
String strCert = cert_begin + cert + end_cert;
byte[] bytes = Base64.decode(cert.getBytes(), Base64.DEFAULT);
InputStream bis = new ByteArrayInputStream(bytes);
try {
trusted.load(bis, "password".toCharArray());
}
catch(Exception e) {
int j;
j = 10;
}
finally {
bis.close();
}
}
AdditionalKeyStoresSSLSocketFactory af = new AdditionalKeyStoresSSLSocketFactory(trusted, null, mTrustCert, mCert);
af.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
return af;
}
catch (Exception e) {
throw new AssertionError(e);
}
}
But this does not seem to be working. When I iterate through my list it is not finding it
Any ideas?
/Loren