java中使用url進(jìn)行編碼和解碼
使用url進(jìn)行編碼和解碼
編碼和解碼的類
java.net.URLDecoder.decode(url,解碼格式) 解碼器.解碼方法。
轉(zhuǎn)化成普通字符串,URLEncoder.decode(url,編碼格式) 將普通字符串變成指定格式的字符串
package com.zixue.springbootmybatis.test;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/** 編碼Encode后都返回了新的字符串,編碼后的字符串不能跨平臺,所以要統(tǒng)一制定編碼格式
* 需要注意的是在url中 "\" '&' '=' ':' '/'都是具有特殊意義的符號,這些符號一旦被編譯后就會失去本身的
* 含義,導(dǎo)致無法被解析,
* 所以在url中需要分塊編碼,
* 解碼Decoder類中decode方法作用是變回成普通字符,其中加號會變成空格,
* */
public class testtest {
public static void main(String[] args) throws UnsupportedEncodingException {
String url = "http://www.baidu.com?name='張三'&age=18 ";
String encodeStr = URLEncoder.encode(url,"UTF-8");
System.out.println(encodeStr);
System.out.println(URLDecoder.decode(encodeStr,"UTF-8"));
}
}

js中的編碼
encodeURL(String url)作用將字符串作為url進(jìn)行編碼,是對url進(jìn)行完整編碼,所有對:?@ & = 是不會進(jìn)行轉(zhuǎn)義的encodeURLComponent()作用是將字符串進(jìn)行編碼,一般用于對某個參數(shù)需要單個編譯的情況下使用,參數(shù)可以是中文
<script >
$(function(){
alert("haha");
var str = 'http://www.baidu.com?name=張三&age=18';
console.log(str);
a(str);
});
function a (s){
var h = encodeURI(s);
console.log(h);
var y = encodeURIComponent("張三");
console.log(y);
var g = "www.baidu.com?name=";
var i = encodeURIComponent("張三");
console.log(g+i);
}
</script>

Java正確URL解碼方式:URLDecoder.decode
Exception in thread "main" java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "u9"
at java.net.URLDecoder.decode(URLDecoder.java:194)
at com.hbzx.controller.PayResultController.main(PayResultController.java:253)
Java調(diào)用 URLDecoder.decode(str, "UTF-8"); 拋出以上的異常,其主要原因是% 在URL中是特殊字符,需要特殊轉(zhuǎn)義一下,
解決辦法
使用%25替換字符串中的%號
?url = url.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
? ?String urlStr = URLDecoder.decode(url, "UTF-8");以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
IntelliJ IDEA 2020.1 EAP4 發(fā)布,重命名/更改簽名新功能一覽
這篇文章主要介紹了IntelliJ IDEA 2020.1 EAP4 發(fā)布,重命名/更改簽名新功能,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04
關(guān)于@SpringBootApplication詳解
這篇文章主要介紹了關(guān)于@SpringBootApplication的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08

