JAVA需要将url读取为字符串和超时选项

JAVA需要将url读取为字符串和超时选项,java,android,Java,Android,已经在另一个帖子中询问过,但没有得到解决方案 看我下面的脚本,我怎么能改变,请完整演示,所以 例如,如果网络关闭,我可以设置一个readtimeout 在所有我必须连接到一个网址,只读一行,得到一个字符串。。。完成 希望你能举个例子。欢迎任何其他工作方式。。thx try { URL url = new URL("http://mydomain/myfile.php"); //url.setReadTimeout(5000); does not work InputStreamReader

已经在另一个帖子中询问过,但没有得到解决方案 看我下面的脚本,我怎么能改变,请完整演示,所以 例如,如果网络关闭,我可以设置一个readtimeout

在所有我必须连接到一个网址,只读一行,得到一个字符串。。。完成 希望你能举个例子。欢迎任何其他工作方式。。thx

try {
URL url = new URL("http://mydomain/myfile.php");

//url.setReadTimeout(5000); does not work

InputStreamReader testi= new InputStreamReader(url.openStream());
BufferedReader in = new BufferedReader(testi);

    //in.setReadTimeout(5000); does not work

stri = in.readLine();   
Log.v ("GotThat: ",stri);
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

使用HttpURLConnection怎么样

import java.net.HttpURLConnection;

   URL url = new URL("http://mydomain/myfile.php");

   HttpURLConnection huc = (HttpURLConnection) url.openConnection();
   HttpURLConnection.setFollowRedirects(false);
   huc.setConnectTimeout(15 * 1000);
   huc.setRequestMethod("GET");
   huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
   huc.connect();
   InputStream input = huc.getInputStream();
从超时中选取的代码:

URL url = new URL("http://www.google.com");
URLConnection conn = url.openConnection();
conn.connect();
conn.setReadTimeout(10000); //10000 milliseconds (10 seconds)

你有什么问题?你到底想干什么?