我该如何解决java.lang.IllegalArgumentException: protocol = https host = null异常?

7

我正在开发一个SSL客户端服务器程序,需要重复使用以下方法。

private boolean postMessage(String message){
    try{ 
         String serverURLS = getRecipientURL(message);

         serverURLS = "https:\\\\abc.my.domain.com:55555\\update";

         if (serverURLS != null){
             serverURL = new URL(serverURLS);
         }

        HttpsURLConnection conn = (HttpsURLConnection)serverURL.openConnection();

        conn.setHostnameVerifier(new HostnameVerifier() { 
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        } 
        });

        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();

        OutputStreamWriter wr = new OutputStreamWriter(os);

        wr.write(message);

        wr.flush();

        if (conn.getResponseCode() != HttpsURLConnection.HTTP_OK)
            return false;
        else
            return true;

    }

这里 ServerURL 的初始化如下:

private URL serverURL = null;

当我尝试执行这个方法时,我在该行收到一个异常:

OutputStream os = conn.getOutputStream();

异常为:
java.lang.IllegalArgumentException: protocol = https host = null

这是什么原因?
3个回答

19

URL使用正斜杠 (/) 而不是反斜杠(如Windows)。尝试:

serverURLS = "https://abc.my.domain.com:55555/update";

你之所以会遇到这个错误,是因为URL类无法解析字符串的主机部分,因此host值为null


3

这段代码似乎完全没有必要:

String serverURLS = getRecipientURL(message);

serverURLS = "https:\\\\abc.my.domain.com:55555\\update";

if (serverURLS != null){
    serverURL = new URL(serverURLS);
}
  1. serverURLS被赋值为getRecipientURL(message)的结果。
  2. 然后立即覆盖了serverURLS的值,使前面的语句成为无用代码
  3. 因为if (serverURLS != null)评估为true,由于您刚刚在前面的语句中分配了变量的值,所以您将一个值分配给serverURL。不可能if (serverURLS != null)评估为false
  4. 实际上,您从未在上一行代码之外使用过变量serverURLS

您可以将所有这些替换为:

serverURL = new URL("https:\\\\abc.my.domain.com:55555\\update");

嗨,那行代码是我加上去的,只是为了检查错误的原因。实际上这个URL是用消息过滤的。请注意,ServerURLs的赋值只是一个测试语句 :) - Chathuranga Chandrasekara

0
可能会对其他人有所帮助 - 我来到这里是因为我错过了在 http: 后面放两个 //。这就是我的错误:

http:/abc.my.domain.com:55555/update


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接