【问题标题】:Causing a MalformedURLException (Android)导致 MalformedURLException (Android)
【发布时间】:2013-12-23 17:14:13
【问题描述】:

我试图在我的代码中引入 MalformedURLException 来测试我对它的处理,但是无论我尝试什么,我似乎都无法导致它。 (我已经传入了一个完整的无意义的非url字符串,它仍然没有出现,我只是得到一个空响应)

我知道android开发者参考描述:

当程序尝试从不正确的规范创建 URL 时,将引发此异常。

我想知道如何创建/提供这样一个不正确的规范

这是我要执行的代码

     try {
        HttpData data = request.composeHttpData();
        //URL url = new URL(composeUrl(data));
        URL url2 = new URL("mydomain:-2/invalidPort");
        HttpsURLConnection conn = (HttpsURLConnection) getHttpClient().open(url2);
        conn.setRequestMethod(data.getMethod());

        //authentication
        addAuthentication(conn);

        //post body
        if (data.getMethod() == POST) {
            conn.setDoOutput(true);
            data.writePostBody(conn.getOutputStream());
            conn.getOutputStream().close();
        }

        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            response.consumeResponse(conn.getInputStream());
        }

        response.setResponseHttpCode(conn.getResponseCode());

    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw new Error("Malformed URL encountered");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        return response;
    }

当我尝试调试代码时,它似乎从 Url 实例化跳转到 return 语句。

【问题讨论】:

  • 从 URL 中删除 http://。

标签: java android exception malformedurlexception


【解决方案1】:

传递一个小于 -1 的端口号

    URL url = new URL("http://mydomain:-2/invalidPort");

【讨论】:

  • 在我的 nexus 7 kitkat 4.4.2 我获得 java.net.MalformedURLException: java.lang.IllegalArgumentException: port
  • 我进一步扩展了这个例子。我认为在此过程中一定有更深层次的错误?
  • 请发布堆栈跟踪,我也在 genymotion 模拟器上尝试过,MalformedURLException 按预期引发
  • 我认为我的问题在于使用 finally 语句。即使我在异常上抛出错误,应用程序也不会崩溃(如我所愿),但无论如何都会继续。
  • 尝试将 return 语句移动到 try 块的最后一行,并删除 finally 块。考虑 finally 应该只包含清理代码
【解决方案2】:

怎么样

throw new MalformedURLException("Testing!");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-05
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 2017-01-13
    相关资源
    最近更新 更多