【问题标题】:malformedURLException when declaring URL with string in Android在Android中用字符串声明URL时出现malformedURLException
【发布时间】:2015-05-10 18:38:30
【问题描述】:

根据 Android 参考,您可以使用字符串声明 URL。

这意味着下一个代码应该是正确的(即):

 URL url = new URL("http://www.android.com/");

当我尝试使用它时,我得到:

“java.net.MalformedURLException”

AndroidStudio 1.2.1.1 上发生在我身上

我尝试使用的完整代码来自Android的HttpURLConnect的参考:

 URL url = new URL("http://www.android.com/");
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
    finally {
     urlConnection.disconnect();
   }
 }

【问题讨论】:

  • 很好,能不能把完整的代码给我看一下,记录错误的getMessage()时看到了什么?
  • 当然,我已经编辑了主帖。
  • 你是否用 try-catch 块包裹了代码块来捕获 MalFormedUrlException ?

标签: android


【解决方案1】:

看看这个:

Java Malformed URL Exception

答案是: 它没有引发错误,它抱怨你没有处理它可能的可能性,即使它不会,因为这种情况下的 URL 不是格式错误的。 Java 似乎认为这是个好主意。 (不是。)

要关闭它,请将 throws MalformedURLException 或 throws IOException 添加到方法声明中。例如:

public void myMethod() throws IOException {
    URL url = new URL("https://wikipedia.org/");
}

【讨论】:

    【解决方案2】:

    这在这里工作得很好

    try {
    
        URL url = new URL("http://www.android.com/");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    
        BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    
        urlConnection.disconnect();
    
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      • 2016-12-05
      相关资源
      最近更新 更多