Din*_*ino 5 java https android http
我目前正在使用以下内容从这里和这里的 Android文档中读取文件.用户选择(在设置屏幕中)他们的站点是使用HTTP还是HTTPS协议.如果他们的网站使用HTTP协议,那么它同时适用于HttpURLConnection和HttpsURLConnection,但如果他们的网站使用HTTPS协议,那么它不工作HttpURLConnection协议,最糟糕的是它并没有给我一个异常错误.下面是我正在使用的示例代码.
所以从本质上讲,我如何检查网址是否为HTTPS协议,以检查用户是否选择了正确的协议?
InputStream inputStream;
HttpURLConnection urlConnection;
HttpsURLConnection urlHttpsConnection;
boolean httpYes, httpsYes;
try {
if (httpSelection.equals("http://")) {
URL url = new URL(weburi);
urlConnection = (HttpURLConnection) url.openConnection();
inputStream = new BufferedInputStream((urlConnection.getInputStream()));
httpYes = True;
}
if (httpSelection.equals("https://")) {
URL url = new URL(weburi);
urlHttpsConnection = (HttpsURLConnection) url.openConnection();
urlHttpsConnection.setSSLSocketFactory(context.getSocketFactory());
inputStream = urlHttpsConnection.getInputStream();
https=True;
}
catch (Exception e) {
//Toast Message displays and settings intent re-starts
}
finally {
readFile(in);
if(httpYes){
urlConnection.disconnect();
httpYes = False;
}
if(httpsYes){
urlHttpsConnection.disconnect();
httpsYes = False;
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
详细说明一下.我需要查看它是否从网站返回有效的回复?因此,如果用户选择http而不是https,我如何检查http是否是不正确的前缀/协议?
如何检查网站是否使用HTTPS或HTTP协议?如果用户只是输入www.google.com并且我附加了https://或http://前缀,我怎么知道哪一个是正确的?
您可以使用android URLUtil来检查url是HTTP还是HTTPS:
public static boolean isHttpUrl (String url)
Returns True iff the url is an http: url.
public static boolean isHttpsUrl (String url)
Returns True iff the url is an https: url.
Run Code Online (Sandbox Code Playgroud)
编辑:
public static boolean isValidUrl (String url)
Returns True iff the url is valid.
Run Code Online (Sandbox Code Playgroud)
URLConnection result = url.openConnection();
if (result instanceof HttpsURLConnection) {
// https
}
else if (result instanceof HttpURLConnection) {
// http
}
else {
// null or something bad happened
}
Run Code Online (Sandbox Code Playgroud)
Din*_*ino -3
我认为这可行,至少看起来可行,你们觉得怎么样?我将此 if 语句放在httpsYes = Trueand之前httpYes = True。
看起来,当选择 HTTPS 协议时,它希望使用响应代码 302 进行重定向,但对于所有其他实例,它使用响应代码 200 连接。我抛出一个新ConnectionException()错误,因为这会将用户带回设置屏幕以更正 URL 错误。
对于 HTTPS 协议:
if (httpsURLConnection.getResponseCode() != 200) {
throw new ConnectException();
}
Run Code Online (Sandbox Code Playgroud)
对于HTTP协议:
if (urlConnection.getResponseCode() != 200) {
throw new ConnectException();
}
Run Code Online (Sandbox Code Playgroud)
评论?我应该使用吗urlConnection.getResponseCode() > 199 && < 300?覆盖所有成功的连接?
| 归档时间: |
|
| 查看次数: |
17681 次 |
| 最近记录: |