Java中如何對(duì)URL進(jìn)行編碼和解碼

小樊
81
2024-09-14 11:19:44

在Java中,可以使用java.net.URLEncoderjava.net.URLDecoder類(lèi)對(duì)URL進(jìn)行編碼和解碼。這兩個(gè)類(lèi)提供了將字符串轉(zhuǎn)換為application/x-www-form-urlencoded MIME格式的方法。

  1. 對(duì)URL進(jìn)行編碼:
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class URLEncodingExample {
    public static void main(String[] args) {
        String url = "https://example.com/search?q=你好世界";
        try {
            String encodedUrl = URLEncoder.encode(url, "UTF-8");
            System.out.println("Encoded URL: " + encodedUrl);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
  1. 對(duì)URL進(jìn)行解碼:
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class URLDecodingExample {
    public static void main(String[] args) {
        String encodedUrl = "https%3A%2F%2Fexample.com%2Fsearch%3Fq%3D%E4%BD%A0%E5%A5%BD%E4%B8%96%E7%95%8C";
        try {
            String decodedUrl = URLDecoder.decode(encodedUrl, "UTF-8");
            System.out.println("Decoded URL: " + decodedUrl);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

注意:在使用URLEncoder.encode()URLDecoder.decode()時(shí),需要指定字符集(如"UTF-8")。這是因?yàn)閁RL編碼和解碼過(guò)程涉及到字符的編碼和解碼。

0