栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

java对url参数编码

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java对url参数编码

import java.io.ByteArrayOutputStream;

import sun.misc.BASE64Decoder;

public class UrlUtils {

public final static String urlEncode(String s) {

try {

return notEmpty(s) ? java.net.URLEncoder.encode(s, "utf-8") : null;

} catch (Exception e) {

return null;

}

}

public static String urlDecode(String s) {

try {

return notEmpty(s) ? java.net.URLDecoder.decode(s, "utf-8") : null;

} catch (Exception e) {

return null;

}

}

public static Boolean notEmpty(String s) {

return s==null||s.trim().length()<1 ? false : true;

}

// 将 s 进行 BASE64 编码

public static String getBASE64(String s) {

if (s == null)

return null;

return (new sun.misc.BASE64Encoder()).encode(s.getBytes());

}

// 将 BASE64 编码的字符串 s 进行解码

public static String getFromBASE64(String s) {

if (s == null)

return null;

BASE64Decoder decoder = new BASE64Decoder();

try {

byte[] b = decoder.decodeBuffer(s);

return new String(b);

} catch (Exception e) {

return null;

}

}

private static String hexString = "0123456789ABCDEF";

public static String encode(String str) {

// 根据默认编码获取字节数组

byte[] bytes = str.getBytes();

StringBuilder sb = new StringBuilder(bytes.length * 2);

// 将字节数组中每个字节拆解成2位16进制整数

for (int i = 0; i < bytes.length; i++) {

sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));

sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));

}

return sb.toString();

}

public static String decode(String bytes) {

ByteArrayOutputStream baos = new ByteArrayOutputStream(

bytes.length() / 2);

// 将每2位16进制整数组装成一个字节

for (int i = 0; i < bytes.length(); i += 2)

baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString

.indexOf(bytes.charAt(i + 1))));

return new String(baos.toByteArray());

}

public static void main(String[] args) throws Exception {

String stest = "http://localhost:8026/loginServlet.do?username='张三'&userpass='123'";

System.out.println(urlEncode(stest));

System.out.println(urlDecode(stest));

System.out.println(UrlUtils.encode("中"));

System.out.println(UrlUtils.decode("D6D0"));

}

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/984584.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号