图一:
示例代码:
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.junit.Test;
public class TestURL {
@Test
public void testOpenStream() {
InputStream is = null;
try {
URL url = new URL("http://v.youku.com/v_show/id_XMTMzMzkxNzg2MA==.html");
/*System.out.println(url.getProtocol());
System.out.println(url.getHost());
System.out.println(url.getPath());
System.out.println(url.getFile());
System.out.println(url.getRef());
System.out.println(url.getQuery());*/
is = url.openStream();
byte[] b = new byte[2048];
int len;
while((len = is.read(b)) != -1) {
String str = new String(b, 0, len);
System.out.print(str);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//如果既有数据的输入,又有数据的输出,则考虑使用URLConnection
@Test
public void testURLConnection() {
InputStream is = null;
try {
URL url = new URL("http://v.youku.com/v_show/id_XMTMzMzkxNzg2MA==.html");
URLConnection urlConn = url.openConnection();
is = urlConn.getInputStream();
byte[] b = new byte[20];
int len;
while((len = is.read(b)) != -1) {
String str = new String(b, 0, len);
System.out.print(str);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}