指定默认值

时间:2012-12-02 14:08:05

标签: java android exception connection serversocket

        URL test = null;
        String inputLine = null;
        BufferedReader in = null;
        try {
            test = new URL("http://localhost/out.php"); // if connection down
        } catch (MalformedURLException e) {
            inputLine = "test_synntax";
        }
        try {
        in = new BufferedReader(new InputStreamReader(test.openStream()));
        ...
  

如果默认情况下URL分辨率失败,如何为输入行指定值   在示例上下文中没有wifi / 3g连接可用,谢谢大家好日子

3 个答案:

答案 0 :(得分:1)

try {
  test = new URL("http://localhost/out.php");
  //I believe you need this and it throws IOException on timeout. 
  //Though it's still unclear to me what you mean by 'resolution' and 'disponible wifi/3g`?
  test.openConnection(); 
} catch (MalformedURLException | IOException e) { 
  inputLine = "test_synntax";
}

这是java的7多重语法,请注意。

答案 1 :(得分:1)

- 如果 wifi / 3g 失败,则会提供UnknownHostException

所以你可以像这样处理它们......

try {
            test = new URL("http://localhost/out.php");

        } catch (UnknownHostException e) {

            inputLine = "Connection error";
   }

答案 2 :(得分:1)

您需要先调用URL.openConnection,然后将默认值放在IOException块中:

try {
   test = new URL("http://localhost/out.php");
   URLConnection urlConn = test.openConnection();
   in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
} catch (MalformedURLException e) {
    inputLine = "test_synntax";
} catch (IOException e) {
    inputLine = "test_synntax";
}