简体   繁体   中英

How to test if my app can connect with https and fallback to http otherwise?

I use the Java HttpURLConnection to connect with my server:

HttpURLConnection connection = null;
try {
  connection = (HttpURLConnection) urlObj.openConnection();
} catch (IOException e) {
  logger.severe("ConnectionImpl - request(): IOException e: "+e.getMessage());
  e.printStackTrace();
}
connection.setDoInput(true);
connection.setRequestMethod("GET");
try {
    connection.connect(); 
  } catch (IOException e) {
    logger.severe("ConnectionImpl - request(): IOException e: "+e.getMessage());
    e.printStackTrace();
}
int statusCode = connection.getResponseCode();

How can I test if my app can connect with https and fail back to http if this fails?

you can do that by applying check on status code as following:

int statusCode = connection.getResponseCode();
if(statusCode==200){
Log.d("Connection Status","Can connect");
}
else{
Log.d("Connection Status","Can't connect");
}

or

if(statusCode == HttpURLConnection.HTTP_OK){
    Log.d("Connection Status","Can connect");
    }
    else{
    Log.d("Connection Status","Can't connect");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM