解决java中对URL编码的问题
首先查看javascript中的encodeURI和encodeURLComponent方法的区别.
encodeURI:不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 也不会对以下在 URI 中具有特殊含义的 ASCII 标点符 号,encodeURI() 函数是不会进行转义的:;/?:@&=+$,#
encodeURLComponent:不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( )
而java中,URLEncoder.encode(string content,String enc) 方法:
不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . *
参考代码如下:
dontNeedEncoding = new BitSet(256);
int i;
for (i = 'a'; i <= 'z'; i++) {
dontNeedEncoding.set(i);
}
for (i = 'A'; i <= 'Z'; i++) {
dontNeedEncoding.set(i);
}
for (i = '0'; i <= '9'; i++) {
dontNeedEncoding.set(i);
}
dontNeedEncoding.set(' '); /* encoding a space to a + is done
* in the encode() method */
dontNeedEncoding.set('-');
dontNeedEncoding.set('_');
dontNeedEncoding.set('.');
dontNeedEncoding.set('*');
如果我想要在java中对一个url进行编码,但是不对URI 中具有特殊含义的 ASCII 标点符号进行编码,需要在dontNeedEncoding中添加相关字符,创建自己的编码类MyURIEncode:
package com.sitech.solr.util; import java.io.CharArrayWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.security.AccessController;
import java.util.BitSet;
import sun.security.action.GetPropertyAction;
public class MyURIEncoder {
static BitSet dontNeedEncoding;
static final int caseDiff = ('a' - 'A');
static String dfltEncName = null; static { /* The list of characters that are not encoded has been
* determined as follows:
*
* RFC 2396 states:
* -----
* Data characters that are allowed in a URI but do not have a
* reserved purpose are called unreserved. These include upper
* and lower case letters, decimal digits, and a limited set of
* punctuation marks and symbols.
*
* unreserved = alphanum | mark
*
* mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
*
* Unreserved characters can be escaped without changing the
* semantics of the URI, but this should not be done unless the
* URI is being used in a context that does not allow the
* unescaped character to appear.
* -----
*
* It appears that both Netscape and Internet Explorer escape
* all special characters from this list with the exception
* of "-", "_", ".", "*". While it is not clear why they are
* escaping the other characters, perhaps it is safest to
* assume that there might be contexts in which the others
* are unsafe if not escaped. Therefore, we will use the same
* list. It is also noteworthy that this is consistent with
* O'Reilly's "HTML: The Definitive Guide" (page 164).
*
* As a last note, Intenet Explorer does not encode the "@"
* character which is clearly not unreserved according to the
* RFC. We are being consistent with the RFC in this matter,
* as is Netscape.
*
*/ dontNeedEncoding = new BitSet(256);
int i;
for (i = 'a'; i <= 'z'; i++) {
dontNeedEncoding.set(i);
}
for (i = 'A'; i <= 'Z'; i++) {
dontNeedEncoding.set(i);
}
for (i = '0'; i <= '9'; i++) {
dontNeedEncoding.set(i);
}
dontNeedEncoding.set(' '); /* encoding a space to a + is done
* in the encode() method */
dontNeedEncoding.set('-');
dontNeedEncoding.set('_');
dontNeedEncoding.set('.');
dontNeedEncoding.set('*'); //对以下在 URI 中具有特殊含义的 ASCII 标点符号 ;/?:@&=+$,# 不需要转义
dontNeedEncoding.set(';');
dontNeedEncoding.set('/');
dontNeedEncoding.set('?');
dontNeedEncoding.set(':');
dontNeedEncoding.set('@');
dontNeedEncoding.set('&');
dontNeedEncoding.set('=');
dontNeedEncoding.set('+');
dontNeedEncoding.set('$');
dontNeedEncoding.set(',');
dontNeedEncoding.set('#'); dfltEncName = AccessController.doPrivileged(
new GetPropertyAction("file.encoding")
);
} /**
* You can't call the constructor.
*/
private MyURIEncoder() { } public static String encode(String s, String enc)
throws UnsupportedEncodingException { boolean needToChange = false;
StringBuffer out = new StringBuffer(s.length());
Charset charset;
CharArrayWriter charArrayWriter = new CharArrayWriter(); if (enc == null)
throw new NullPointerException("charsetName"); try {
charset = Charset.forName(enc);
} catch (IllegalCharsetNameException e) {
throw new UnsupportedEncodingException(enc);
} catch (UnsupportedCharsetException e) {
throw new UnsupportedEncodingException(enc);
} for (int i = 0; i < s.length();) {
int c = (int) s.charAt(i);
//System.out.println("Examining character: " + c);
if (dontNeedEncoding.get(c)) {
if (c == ' ') {
c = '+';
needToChange = true;
}
//System.out.println("Storing: " + c);
out.append((char)c);
i++;
} else {
// convert to external encoding before hex conversion
do {
charArrayWriter.write(c);
/*
* If this character represents the start of a Unicode
* surrogate pair, then pass in two characters. It's not
* clear what should be done if a bytes reserved in the
* surrogate pairs range occurs outside of a legal
* surrogate pair. For now, just treat it as if it were
* any other character.
*/
if (c >= 0xD800 && c <= 0xDBFF) {
/*
System.out.println(Integer.toHexString(c)
+ " is high surrogate");
*/
if ( (i+1) < s.length()) {
int d = (int) s.charAt(i+1);
/*
System.out.println("\tExamining "
+ Integer.toHexString(d));
*/
if (d >= 0xDC00 && d <= 0xDFFF) {
/*
System.out.println("\t"
+ Integer.toHexString(d)
+ " is low surrogate");
*/
charArrayWriter.write(d);
i++;
}
}
}
i++;
} while (i < s.length() && !dontNeedEncoding.get((c = (int) s.charAt(i)))); charArrayWriter.flush();
String str = new String(charArrayWriter.toCharArray());
byte[] ba = str.getBytes(charset);
for (int j = 0; j < ba.length; j++) {
out.append('%');
char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
// converting to use uppercase letter as part of
// the hex value if ch is a letter.
if (Character.isLetter(ch)) {
ch -= caseDiff;
}
out.append(ch);
ch = Character.forDigit(ba[j] & 0xF, 16);
if (Character.isLetter(ch)) {
ch -= caseDiff;
}
out.append(ch);
}
charArrayWriter.reset();
needToChange = true;
}
} return (needToChange? out.toString() : s);
}
}
解决java中对URL编码的问题的更多相关文章
- java中的url 编码与解码
什么是application/x-www-form-urlencoded字符串? 答:它是一种编码类型.当URL地址里包含非西欧字符的字符串时,系统会将这些字符转换成application/x-www ...
- 浅谈利用同步机制解决Java中的线程安全问题
我们知道大多数程序都不会是单线程程序,单线程程序的功能非常有限,我们假设一下所有的程序都是单线程程序,那么会带来怎样的结果呢?假如淘宝是单线程程序,一直都只能一个一个用户去访问,你要在网上买东西还得等 ...
- python中的URL编码和解码
python中的URL编码和解码:test.py # 引入urllib的request模块 import urllib.request url = 'https://www.douban.com/j/ ...
- Delphi中处理URL编码解码
Delphi中处理URL编码解码 一.URL简单介绍 URL是网页的地址,比方 http://www.shanhaiMy.com. Web 浏览器通过 URL 从 web server请求页面 ...
- java,javascript中的url编码
真实场景 url示例如下 http://localhost:31956/Login/Auto?Token=e8a67a9f-c062-4964-b703-d79f29c8b64e&Return ...
- 记录Java中对url中的参数进行编码
Code: import java.net.URLEncoder; import java.util.HashMap; import java.util.Iterator; import java.u ...
- 我对JavaWeb中中文URL编码的简单总结
1.application/x-www-form-urlencoded 它是一种编码类型.当URL地址里包含非西欧字符的字符串时,系统会将这些字符转换成application/x-www-form-u ...
- java中的字符编码方式
1. 问题由来 面试的时候被问到了各种编码方式的区别,结果一脸懵逼,这个地方集中学习一下. 2. 几种字符编码的方式 1. ASCII码 我们知道,在计算机内部,所有的信息最终都表示为一个二进制的字符 ...
- js和java中URI的编码和解码
js中对文字进行编码主要有三个函数:escape,encodeURI,encodeURIComponent: 对应解码为:unescape,decodeURI,decodeURIComponent 这 ...
随机推荐
- 记拿到鹅厂前端开发暑期实习offer的经历
#想起来时的路 在真正拿到腾讯实习offer之前,也是看过不少人的面经,心生向往.很早在入前端坑之前,我就想着大四的时候有机会要尝试去腾讯里实习. 大一入门语言就是C++,这让我很无奈,所以我很快的就 ...
- java应用maven插件动态生成webservice代码
pom.xml如下 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www ...
- mysql语句收藏
1.说明:创建数据库 CREATE DATABASE database-name 2.说明:删除数据库 drop database dbname 3.说明:备份sql server --- 创建 备份 ...
- 关于设置MX记录
简介:正确设置MX(Mail Exchanger)邮件交换记录是企业电子邮件服务稳定运行的基本条件,我们经常发现很多企业电子邮箱管理员因为设置了不符合规范的MX记录,导致重要的外部邮件退回或者丢失. ...
- fastscript调用delphi方法和DELPHI调用FASTSCRIPT方法
fastscript调用Delphi过程: 1. 先创建事件处理方法:TfsCallMethodEvent 2. 然后再用调用TfsScript.AddMethod方法,第一个参数为Delphi方法 ...
- Castle IOC容器构建配置详解(二)
主要内容 1.基本类型配置 2.Array类型配置 3.List类型配置 4.Dictionary类型配置 5.自定义类型转换 一.基本类型配置 在Castle IOC的配置文件中,大家可能都已经注意 ...
- CSS3- px、em、rem区别介绍
PX px像素(Pixel).相对长度单位.像素px是相对于显示器屏幕分辨率而言的. PX特点 1. IE无法调整那些使用px作为单位的字体大小: 2. 国外的大部分网站能够调整的原因在于其使用了em ...
- uva140 - Bandwidth
Bandwidth Given a graph (V,E) where V is a set of nodes and E is a set of arcs in VxV, and an orderi ...
- CentOS 6.4安装本地yum源,并安装X Window System
1.为DVD创建一个挂载目录 [root@localhost ~]# mkdir /media/CentOS 2.在Linux下挂载CentOS DVD(虚拟机挂载DVD不说了,应该都会) [root ...
- C++学习笔记之继承
一.基类和派生类 很多时候,一个类的对象也“是”另一个类的对象,如矩形是四边形,在C++中,矩形类Rectangle可以由四边形类Quad继承而来,于是,四边形类Quad是基类,矩形类Rectangl ...