java 检查 URL 是 HTTPS 还是 HTTP 协议?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30411059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:04:23  来源:igfitidea点击:

Check if URL is HTTPS or HTTP protocol?

javaandroidhttphttps

提问by Dino

I am currently using the following to read a file from android docs hereand here. The user selects (in the settings screen) if their site uses HTTP or HTTPS protocol. If their website uses the HTTP protocol then it works for both HttpURLConnectionand HttpsURLConnection, but if their site uses HTTPS protocol then it doesn't work for HttpURLConnectionprotocol and worst of all it doesn't give me an exception error. Below is the sample code that I am using.

我目前正在使用以下内容从此处此处的android 文档中读取文件。用户选择(在设置屏幕中)他们的站点是使用 HTTP 还是 HTTPS 协议。如果他们的网站使用 HTTP 协议,那么它适用于HttpURLConnectionHttpsURLConnection,但如果他们的网站使用 HTTPS 协议,那么它不适用于HttpURLConnection协议,最糟糕的是它不会给我一个异常错误。下面是我正在使用的示例代码。

So in essence, how can I check to see if the web url is HTTPS protocol so checking if the user selected the correct protocol?

所以从本质上讲,我如何检查 web url 是否是 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;
 } 
}
}

EDIT:

编辑:

To elaborate some more. I need to see if it returns a valid response from a website? So if the user selected http instead of https how can I check to see if http is the incorrect prefix/protocol?

再详述一些。我需要查看它是否从网站返回有效响应?因此,如果用户选择了 http 而不是 https,我如何检查 http 是否是不正确的前缀/协议?

How can I check if the website uses HTTPS or HTTP protocol? If the user then only puts in say www.google.comand I append https://or http://prefix to it, how do I know which one is the correct one to use?

如何查看网站使用的是HTTPS还是HTTP协议?如果用户然后只输入www.google.com并且我附加https://http://前缀,我怎么知道哪个是正确的使用?

采纳答案by Dino

I think this works, at least it seems to be working, what do you guys think? I place this if statement just before the httpsYes = Trueand httpYes = True.

我认为这有效,至少它似乎有效,你们怎么看?我把这个 if 语句放在httpsYes = Trueand之前httpYes = True

It seems that when the HTTPS protocol is selected it wants to redirect using response code 302, but for all other instances it connects with response code 200. I throw a new ConnectionException()error as that takes the user back to the settings screen to correct the URL error.

似乎选择了HTTPS协议时,它想要使用响应代码302重定向,但是对于所有其他实例,它与响应代码200连接。我抛出了一个新的ConnectionException()错误,因为它将用户返回设置屏幕以纠正URL错误.

For the HTTPS protocol:

对于 HTTPS 协议:

if (httpsURLConnection.getResponseCode() != 200) {
     throw new ConnectException();
}

For the HTTP protocol:

对于 HTTP 协议:

if (urlConnection.getResponseCode() != 200) {
     throw new ConnectException();
}

Comments? Should I use urlConnection.getResponseCode() > 199 && < 300? To cover all successful connects?

评论?我应该使用urlConnection.getResponseCode() > 199 && < 300吗?覆盖所有成功连接?

回答by Dhaval Patel

You can Use android URLUtilto check whether url is HTTP or HTTPS:

您可以使用 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.

Edit:

编辑:

public static boolean isValidUrl (String url)
Returns True iff the url is valid.

回答by Bojan Kseneman

URLConnection result = url.openConnection();
if (result instanceof HttpsURLConnection) {
   // https
}
else if (result instanceof HttpURLConnection) {
   // http
}
else {
  // null or something bad happened
}

回答by Kartheek

This can be checked by using Util.

这可以通过使用Util来检查。

  • isHttpUrlreturns True iff the url is an http: url.
  • isHttpsUrlreturns True iff the url is an https: url.
  • isHttpUrl返回 True 如果 url 是 http: url。
  • isHttpsUrl返回 True 如果 url 是 https: url。

回答by Shailesh

I have checked URLUtilclass and checked that its contain so many methods for these kind of stuff, but i just extend the answer that you can simply do as below also :-

我已经检查了URLUtil类并检查了它是否包含用于此类内容的许多方法,但我只是扩展了您可以简单地执行以下操作的答案:-

public static boolean isHttpOrHttpsUrl(String url) {
        String patter = "^(http|https|ftp)://.*$";
        if (url.matches(patter)){
            return true;
        }else{
            return false;
        }
    }

回答by Ashnet

Try this code:

试试这个代码:

mConnexion = (URLUtil.isHttpsUrl(mStringUrl)) ? (HttpsURLConnection) url.openConnection() : (HttpURLConnection) url.openConnection();

回答by Antwan

you can try this

你可以试试这个

    boolean httpYes, httpsYes;
     try {

      URL url = new URL(weburi);
      urlConnection = (HttpURLConnection) url.openConnection();
      inputStream = new BufferedInputStream((urlConnection.getInputStream()));
    httpYes = True;
    }


    catch (Exception e) {
    //Toast Message displays and settings intent re-starts
          URL url = new URL(weburi);
          urlHttpsConnection = (HttpsURLConnection) url.openConnection();
          urlHttpsConnection.setSSLSocketFactory(context.getSocketFactory());
          inputStream = urlHttpsConnection.getInputStream();
          https=True;
    }

回答by Armando Cordova

My recommendation is created function expression regular. for example:

我的建议是创建函数表达式正则。例如:

public void testUrl(Object urlHttp){

    String url = "https://www.google.com";

    if(url.matches("^(https?)://.*$")){
     Object o = (HttpsURLConnection) urlHttp;
    }else{
     Object o = (HttpURLConnection) urlHttp;
    }
}

Regards

问候