如何测试我的应用程序是否可以与https连接并以其他方式回退到http?

时间:2015-09-16 21:28:02

标签: java android http https httpurlconnection

我使用Java HttpURLConnection连接我的服务器:

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();

我如何测试我的应用是否可以与https连接,如果失败则会失败回到http?

1 个答案:

答案 0 :(得分:0)

您可以通过检查状态代码来执行此操作,如下所示:

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

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