如果没有输入,请从URL获取协议

时间:2015-02-15 15:17:53

标签: java android

我正在尝试找到一种从用户输入的URL中获取协议的方法。我在Android布局文件中将EditText设置为uri。用户在其网址中输入 www.thiersite.com theirsite.com

现在我如何从他们输入的内容中获得正确的协议?似乎无处不在,我认为您需要 https:// http:// 作为http请求中的协议。当我没有针对其网址的协议时,我会收到格式错误的异常。

有没有办法检查URL,而无需在输入地址时使用协议?所以从本质上讲,我是否需要要求用户输入协议作为URL的一部分?我更愿意以编程方式进行。

1 个答案:

答案 0 :(得分:1)

/**
* Protocol value could be http:// or https://
*/
boolean usesProtocol(String url,String protocol){
    boolean uses = false;
    try{
        URL u = new URL( protocol.concat(url) );
        URLConnection con = u.openConnection();
        con.connect();
        // the following line will be hit only if the 
        // supplied protocol is supported
        uses = true;
    }catch(MalformedURLException e){
        // new URL() failed
        // user has made a typing error
    }catch(IOException e){
        // openConnection() failed
        // the supplied protocol is not supported
    }finally{
        return uses;
    }
}  

我相信代码是自我解释的。上面的代码不使用外部依赖项。如果您不介意使用JSoup,那么SO上的另一个答案就是处理相同的问题:Java how to find out if a URL is http or https?

我的来源:http://docs.oracle.com/javase/tutorial/networking/urls/connecting.html

相关问题