package just4test;
import java.net.*;
import java.io.*;
import java.util.*;
public class Urltest {
public static void main(String[] args) {
try
{
Scanner emm = new Scanner(System.in);
URL url = new URL(emm.next());//构造url对象
URLConnection urlConnection = url.openConnection();//连接开启!
HttpURLConnection connection = null;
if(urlConnection instanceof HttpURLConnection)//防止抛出错误,先进行类型检查再强转
{
connection = (HttpURLConnection) urlConnection;
}
else
{
System.out.println("请输入 URL 地址");
return;
}
//原文用的是inputStreamReader,显然用Scanner更吼,但这里重复了连接步骤
Scanner cin = new Scanner(url.openStream());
/*贴一下稍改过的原文写法,指利用的是inputStreamer对象来构造Scanner,好处是不用再连接一次
*Scanner cin = new Scanner(
new InputStreamReader(connection.getInputStream()));
*/
String urlString = "";
while(cin.hasNextLine())
{
urlString += cin.nextLine();
}
System.out.println(urlString);
}catch(IOException e)
{
e.printStackTrace();
}
}
}
看着别人博客自己瞎敲的,编码问题暂时没解决,所以汉字会乱码,一会再研究下