无法从URL读取(Android)

时间:2012-02-10 17:54:23

标签: android web-services http

我有一个家庭作业,我必须从文件中加载代码行并将它们输出到log cat中。这是我的代码:

private void readFromURL (String requestedURL){

    try {
        URL myurl = new URL (requestedURL);
        InputStream mystream = myurl.openStream(); 
        Scanner myscan = new Scanner (mystream); 

        while (myscan.hasNextLine()) {
            String aLine = myscan.nextLine(); 
            Log.d ("works", aLine);
        }
    }
    catch (MalformedURLException oops) {
                Log.d ("ERROR" , "Are you sure the URL is correct?" + oops);
    }
    catch (IOException oops_again)
    {
                Log.d ("ERROR", "Can't access the remote resource: " + oops_again);
    }
} 

通过单击按钮调用readFromURL方法。每当我运行应用程序时,我都会收到IOException并显示“无法访问远程资源:”。在日志猫。

我试图从中获取信息的网址是:http://www.cis.gvsu.edu/~dulimarh/CS163H/courses.cgi

我已将清单中的权限添加到互联网中。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

使用以下内容获取InputStream数据以执行您所需的操作:

private InputStream downloadUrl(String url) {
  HttpURLConnection con = null;
  URL url;
  InputStream is=null;
  try {
    url = new URL(url);
    con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.setDoInput(true);
    // Start the query
    con.connect();
    is = con.getInputStream();
  }catch (IOException e) {
    //handle the exception !
    e.printStackTrace();
  }
  return is; 
}

使用此功能,您应该能够使用InputStreamLog.d 回显 - 您应该能够找出该部分;)

相关问题