Java-网络编程 url
Java URL处理
-
基本格式
protocol://host:port/path?query#fragment //协议://主机:端口/文件路径?请求参数#定位元素
-
URL类方法--可以通过
java.net.URL
构建和获取资源-
public URL(String protocol, String host, int port, String file) throws MalformedURLException
通过给定的参数(协议、主机名、端口号、文件名)创建URL -
public URL(String protocol, String host, String file) throws MalformedURLException
使用指定的协议、主机名、文件名创建URL,端口使用协议的默认端口 -
public URLConnection openConnection() throws IOException
打开一个URL连接,并运行客户端访问资源import java.net.*; import java.io.*; public class URLDemo { public static void main(String [] args) { try{ URL url = new URL("http:/..."); System.out.println("URL 为:" + url.toString()); System.out.println("协议为:" + url.getProtocol()); System.out.println("验证信息:" + url.getAuthority()); System.out.println("文件名及请求参数:" + url.getFile()); System.out.println("主机名:" + url.getHost()); System.out.println("路径:" + url.getPath()); // 还有很多。。。 }catch(IOException e) { e.printStackTrace(); } } }
-
-
URLConnections
类方法
openConnection()
返回一个java.net.URLConnection
import java.net.*; import java.io.*; public class URLConnDemo { try { URL url = new URL("http://..."); URLConnection urlConnection = url.openConnection(); HttpURLConnection connection = null; if(urlConnection instanceof HttpURLConnection) { connection = (HttpURLConnection) urlConnection; } else { System.out.println("请输入URL地址"); return; } BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream())); String urlString = ""; String current; while((current = in.readLine()) != null) { urlSrtring += current; } System.out.println(urlString); }catch(IOException e) { e.printStackTrace(); } }
春天的雨,夏天的风,只为更好的自己和最爱的你!