Java网络编程之URL

来源:互联网 发布:郑州丰泽教育编程 编辑:程序博客网 时间:2024/05/02 02:03

图一:

示例代码:

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 {@Testpublic 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@Testpublic 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();}}}}}


0 0
原创粉丝点击