在尝试将我的 android 应用程序转换为使用 SSL 在我的 android 应用程序和 Web 服务器之间传输信息后,我遇到了一些问题。(SocketTimeOutException)
我从证书颁发机构 (CA) 购买了正 SSL 证书,并将我的服务器配置为正确使用它。我已经在我的网络浏览器中对其进行了测试,并且它工作正常。
现在我正在尝试修改我的 android 应用程序以使用 https 而不是 http,但由于这是我自己第一次使用 https,所以我对需要在 java 代码中实现哪些步骤感到有些困惑。
目前我正在我的设置页面上配置我的应用程序以使用正确的 url。例如,我在输入网站 url (http://www.mydomain.com) 和存储相关页面的应用程序文件夹 (myappfolder) 的活动中有 2 个文本字段
然后,我使用以下代码进行连接并测试连接变量是否配置正确,其中 validateurl.aspx 是一个网页,如果页面存在则返回 JSON 字符串:
protected boolean validateConnectionSettings() {
String result = "";
boolean validated = false;
try {
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(tvWebsiteURLValue.getText() + File.separator + tvApplicationMiddlewareValue.getText() + File.separator + "validateurl.aspx");
URL url = new URL(urlBuilder.toString());
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();
URLConnection urlConn = url.openConnection();
BufferedReader in = new BufferedReader( new InputStreamReader(urlConn.getInputStream()));
String inputLine;
while((inputLine = in.readLine()) != null){
result += inputLine;
}
in.close();
if(result.equals("exists")) {
validated = true;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
}
return validated;
}
现在,当我尝试将 (http://www.mydomain.com) 变量转换为使用 https 时,我得到了上面提到的 java.net.SocketTimeoutException。
我已经用谷歌搜索了这个问题,发现我应该在上面的代码中实现 HttpsURLConnection 而不是 URLConnection 所以我已经相应地修改了我的代码如下:
protected boolean validateConnectionSettings() {
String result = "";
boolean validated = false;
try {
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(tvWebsiteURLValue.getText() + File.separator + tvApplicationMiddlewareValue.getText() + File.separator + "validateurl.aspx");
URL url = new URL(urlBuilder.toString());
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();
// URLConnection urlConn = url.openConnection();
HttpsURLConnection urlConn = (HttpsURLConnection)url.openConnection();
BufferedReader in = new BufferedReader( new InputStreamReader(urlConn.getInputStream()));
String inputLine;
while((inputLine = in.readLine()) != null){
result += inputLine;
}
in.close();
if(result.equals("exists")) {
validated = true;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
}
return validated;
}
但是我仍然收到 java.net.SocketTimeoutException。任何想法我做错了什么?