这是我参与2022首次更文挑战的第35天,活动详情查看:2022首次更文挑战
Java程序设计 网络编程 URL与URLConnection类、URLEncoder类与URLDecoder类
URL
URL(Uniform Resource Locator)统一资源定位符,可以直接使用此类找到互联网上的资源
URL类
方法 | 作用 |
---|---|
public URL(String spec) throws MalformedURLException | 根据指定的地址实例化URL对象 |
public URL(String prolocol,String host,int port,String file) throws MalformedURLException | 实例化URL对象,并指定协议、主机、端口名称、资源文件 |
public URLConnection openConnection() throws IOException | 取得一个URLConnection对象 |
public final InputStream openStream() throws IOException | 取得输入流 |
使用URL读取内容
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class Hello {
public static void main(String[] args) throws IOException {
URL url = new URL("http","www.baidu.com",
80,"/index.html");
InputStream input = url.openStream();
Scanner scan = new Scanner(input);
scan.useDelimiter("\n");
while (scan.hasNext()){
System.out.println(scan.next());
}
}
}
URLConnection类
URLConnection是封装访问远程网络资源一般方法的类,通过它可以建立与远程服务器的连接,检查远程资源的一些属性
URLConnection类
方法 | 作用 |
---|---|
public int getContentLength() | 取得内容的长度 |
public String getContentType() | 取得内容的类型 |
public InputStream getInputStream() throws IOException | 取得连接的输入流 |
取得URL的信息
import java.net.URL;
import java.net.URLConnection;
public class Hello {
public static void main(String[] args) throws Exception{
URL url = new URL("http://www.baidu.com");
URLConnection urlCon = url.openConnection();
System.out.println("内容大小:"+urlCon.getContentLength());
System.out.println("内容类型:"+urlCon.getContentType());
}
}
URLEncoder类与URLDecoder类
使用URL访问时,经常会看到在地址后有很多其他的附带信息
从这些地址的附带信息上可以发现英文单词可以正常显示,但是对于中文的话,则会将其进行一系列的编码操作
在Java中如果要想编码和解码操作就必须使用URLEncoder和URLDecoder两个类
URLEncoder类
方法 | 作用 |
---|---|
public static String encode(String s,String enc) throws UnsupportedEncodingException | 使用指定的编码机制将字符串转换为application/x-www-form-urlencoded格式 |
URLDecoder类
方法 | 作用 |
---|---|
public static String decode(String s,String enc) throws UnsupportedEncodingException | 使用指定的编码机制对application/x-www-form-urlencoded字符串解码 |
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
public class Hello {
public static void main(String[] args) throws UnsupportedEncodingException {
String word = "小旺";
String encode = URLEncoder.encode(word,"UTF-8");
System.out.println("编码后:"+encode);
String decode = URLDecoder.decode(encode,"UTF-8");
System.out.println("解码后:"+decode);
}
}
与url中wd=后的编码相对应