学会使用 URL、使用 URLConnection、 URL 编码和解码

159 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

  1. 定义打开 sohu 网的 URL,显示 sohu 网的 协议 、端口 、主机 。

实现代码:

 package com.zhangyufan.net;
 ​
 import java.io.IOException;
 import java.net.URL;
 ​
 public class TestURL {
 ​
     public static void main(String[] args) throws IOException {
         URL url = new URL("https://www.sohu.com/");
         System.out.println("sohu网的协议为: " + url.getProtocol() + " ,端口为: " + url.getPort() + " ,主机为: " + url.getHost());
     }
 ​
 }
 ​

运行结果:

在这里插入图片描述

  1. 使用 URLConnection 读出 sina 主页的内容 显示其内容大小 显示其内容类型

实现代码:

 package com.zhangyufan.net;
 ​
 import java.io.IOException;
 import java.net.URL;
 import java.net.URLConnection;
 ​
 public class TestURLConnection {
 ​
     public static void main(String[] args) throws IOException {
         URL localURL = new URL("https://www.sina.com.cn/");
         URLConnection connection = localURL.openConnection();
         System.out.println("sina主页内容大小: " + connection.getContentLength());
         System.out.println("sina主页内容类型: " + connection.getContentType());
     }
 ​
 }
 ​

运行结果:

在这里插入图片描述

  1. 写一段代码,把“我很努力学习 java”进行编码,输出 然后再进行解码,输出

实现代码:

 package com.zhangyufan.net;
 ​
 import java.io.UnsupportedEncodingException;
 import java.net.URLDecoder;
 import java.net.URLEncoder;
 ​
 public class TestURLEncoderURLDecoder {
 ​
     public static void main(String[] args) throws UnsupportedEncodingException {
         String str = "我很努力学习java";
         String encode = URLEncoder.encode(str, "utf-8");
         System.out.println("编码之后的内容为: " + encode);
         String decode = URLDecoder.decode(encode, "utf-8");
         System.out.println("解码之后的内容为: " + decode);
 ​
     }
 ​
 }
 ​

运行结果: 在这里插入图片描述