bufferReader或InputStreamReader始终抛出异常

时间:2011-01-18 21:52:35

标签: java android web-services

我创建了一个java程序,它只会读取一个网页代码...谷歌的例子,它工作正常。但是我试图在模拟器和实际设备-Droid X上的Android应用程序中实现相同的代码。

我尝试了两种不同的方法,并且发现它是抛出IOException的同一行。它是创建新bufferReader的行。我不知道它是bufferReader还是InputStreamReader。此外,我真的不知道除了打印IOException之外如何从异常中获取更多信息。这是重要的代码被剥离。感谢。

try
        {
//method 1
         URL page = new URL("http://192.168.1.108/score.php");
         URLConnection pageconnection = page.openConnection();
         BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    pageconnection.getInputStream()));

//method 2
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            BufferedReader rd  = new BufferedReader(new InputStreamReader(conn.getInputStream()));

while ((inputLine = rd.readLine()) != null) 
            System.out.println(inputLine);

          in.close();
          rd.close();
            HscoreText.setText("It Worked!");
        }
        catch(MalformedURLException e)
        {
         HscoreText.setText("MalformedURL");
        }
        catch (IOException e)
        {
         HscoreText.setText("IOException");
        }

4 个答案:

答案 0 :(得分:0)

而不是这样做,

HscoreText.setText("IOException");

你可以这样做。

HscoreText.setText(e.getMessage());

查看异常消息。您是说您的代码在Android之外运行?

尝试重新启动Eclipse和模拟器。尝试使用其他网址。

答案 1 :(得分:0)

值得注意的是,您的代码(两个版本)都假定返回的HTML具有与平台默认编码相同的字符编码。即使服务器在同一台计算机上运行,​​也可能不是这样。

答案 2 :(得分:0)

无耻插件你可以使用Resty而不用担心URLConnection和东西。

Resty r = new Resty();
String text = r.text("http://192.168.1.108/score.php").toString();

它会尊重内容编码,否则就会让您失望。

答案 3 :(得分:-1)

在conn.connect();

之后试试这个 - setDoInput(true)和setDoOutput(true)