本文主要是介绍2 url与URLConnection使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
例子1
package add.socket.url;import java.net.MalformedURLException;
import java.net.URL;public class URLTest01 {public static void main(String[] args) {try {URL myURL = new URL("http://java.sun.com:80/docs/books/tutorial/index.html#DOWN");/** URL myURL = new URL( "http://www.baidu.com");*/String protocal = myURL.getProtocol();System.out.println("protocal = " + protocal); // protocal = httpString host = myURL.getHost();System.out.println("host = " + host); // host = java.sun.comint port = myURL.getPort();System.out.println("port = " + port); // port = 80String file = myURL.getFile();System.out.println("file = " + file); // file =// /docs/books/tutorial/index.htmlString ref = myURL.getRef();System.out.println("ref = " + ref); // ref = DOWN} catch (MalformedURLException e) {e.printStackTrace();}}}
例子2:
package add.socket.url;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;public class UrlConnection01 {/*** 为获得URL的实际比特或内容信息,用它的openConnection()方法从它创建一个URLConnection对象,* 与调用URL对象相关,它返回一个URLConnection对象。它可能引发IOException异常。* URLConnection是访问远程资源属性的一般用途的类。* @throws IOException */public static void main(String[] args) throws IOException {URL url = new URL("http://localhost:8080/day09/testParam.html");/* // 打开连接URLConnection conn = url.openConnection();// 得到输入流InputStream is = conn.getInputStream();*///上面两句等价于下面的一句,InputStream is = url.openStream();// 关于IO流的用法和写法一定要熟悉OutputStream os = new FileOutputStream("e:\\baidu.txt"); //如果没有可创建文件byte[] buffer = new byte[2048];int length = 0;//将访问的网页写入文件while (-1 != (length = is.read(buffer, 0, buffer.length))){os.write(buffer, 0, length);}is.close();os.close();}}
例子3
package add.socket.url;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;public class UrlConnection03 {public static void main(String[] args) throws IOException {URL url = new URL("http://localhost:8080/day09/testParam.html");BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));/* 如果需要转码* BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); */String line = null;while(null != (line = br.readLine())){System.out.println(line);}br.close();}}
这篇关于2 url与URLConnection使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!