java如何实现python的urllib.quote(str,safe='/')
最近需要将一些python代码转成java,遇到url编码
urllib.quote(str,safe='/')
但java中URLEncoder.encode(arg, Constant.UTF_8)会将'/'转成%2F
网上查了一下 java没见到类似的safe方式,只好自己实现一个类
package com.ppc.spider.fc.util;
import java.io.ByteArrayOutputStream;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.io.CharArrayWriter;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException ;
import java.util.BitSet;
import java.security.AccessController;
import sun.security.action.GetPropertyAction; public class UrlSafeEncoder { 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('*'); dfltEncName = AccessController.doPrivileged(
new GetPropertyAction("file.encoding")
);
} /**
* You can't call the constructor.
*/
private UrlSafeEncoder() { }
/**
* Translates a string into {@code application/x-www-form-urlencoded}
* format using a specific encoding scheme. This method uses the
* supplied encoding scheme to obtain the bytes for unsafe
* characters.
* <p>
* <em><strong>Note:</strong> The <a href=
* "http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars">
* World Wide Web Consortium Recommendation</a> states that
* UTF-8 should be used. Not doing so may introduce
* incompatibilities.</em>
*
* @param s {@code String} to be translated.
* @param enc The name of a supported
* <a href="../lang/package-summary.html#charenc">character
* encoding</a>.
* @return the translated {@code String}.
* @exception UnsupportedEncodingException
* If the named encoding is not supported
* @see URLDecoder#decode(java.lang.String, java.lang.String)
* @since 1.4
*/
public static String encode(String s, String enc,char safe)
throws UnsupportedEncodingException {
dontNeedEncoding.set(safe);
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);
}
}
验证下 基本ok
java如何实现python的urllib.quote(str,safe='/')的更多相关文章
- Python urllib.quote
转: 编码:urllib.quote(string[, safe]),除了三个符号“_.-”外,将所有符号编码,后面的参数safe是不编码的字符, 使用的时候如果不设置的话,会将斜杠,冒号,等号,问号 ...
- python爬虫-urllib模块
urllib 模块是一个高级的 web 交流库,其核心功能就是模仿web浏览器等客户端,去请求相应的资源,并返回一个类文件对象.urllib 支持各种 web 协议,例如:HTTP.FTP.Gophe ...
- python:利用urllib查找计算机二级准考证号
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAaYAAAEACAIAAAB3VkWnAAAgAElEQVR4nOydZ3gUR9bv+WhExhHnDH
- python模块—urllib
1. 网页操作 urllib.urlopen(url[,data[,proxies]]) 打开一个url,返回一个文件对象,然后可以进行类似文件对象操作 url:远程数据的路径,即网址 data:表示 ...
- python爬虫 - Urllib库及cookie的使用
http://blog.csdn.net/pipisorry/article/details/47905781 lz提示一点,python3中urllib包括了py2中的urllib+urllib2. ...
- 在Java中调用Python
写在前面 在微服务架构大行其道的今天,对于将程序进行嵌套调用的做法其实并不可取,甚至显得有些愚蠢.当然,之所以要面对这个问题,或许是因为一些历史原因,或者仅仅是为了简单.恰好我在项目中就遇到了这个问题 ...
- python爬虫 urllib模块url编码处理
案例:爬取使用搜狗根据指定词条搜索到的页面数据(例如爬取词条为‘周杰伦'的页面数据) import urllib.request # 1.指定url url = 'https://www.sogou. ...
- Python使用urllib,urllib3,requests库+beautifulsoup爬取网页
Python使用urllib/urllib3/requests库+beautifulsoup爬取网页 urllib urllib3 requests 笔者在爬取时遇到的问题 1.结果不全 2.'抓取失 ...
- Atitit.http代理的实现 代码java php c# python
Atitit.http代理的实现 代码java php c# python 1. 代理服务器用途 代理服务器看成是一种扩展浏览器功能的途径.例如,在把数据发送给浏览器之前,可以用代理服务器压缩数据 调 ...
随机推荐
- Task 回调
前正无生意,且记录Task回调之用法. using System; using System.Collections.Generic; using System.Diagnostics; using ...
- UIView 动画
1.UIView 动画 核心动画 和 UIView 动画 的区别: 核心动画一切都是假象,并不会真实的改变图层的属性值,如果以后做动画的时候,不需要与用户交互,通常用核心动画(转场). UIView ...
- 「BZOJ 1876」「SDOI 2009」SuperGCD「数论」
题意 求\(\gcd(a, b)\),其中\(a,b\leq10^{10000}\) 题解 使用\(\text{Stein}\)算法,其原理是不断筛除因子\(2\)然后使用更相减损法 如果不筛\(2\ ...
- luoguP3224 [HNOI2012]永无乡
https://www.luogu.org/problemnew/show/P3224 考虑对每个岛维护一颗平衡树,用并查集维护连通性,启发式合并即可 这东西其实是一个大暴力,每次把节点少的平衡树合并 ...
- 微信小程序获取用户手机号,服务器解码demo
原理:通过微信登陆接口wx.login得到encryptedData . iv .code.经过接口处理code得到sessionkey.最后官方demo得到解密后的手机号.(接口处理这一步也可以在 ...
- [SCOI2009]windy数 BZOJ1026 数位dp
题目描述 windy定义了一种windy数.不含前导零且相邻两个数字之差至少为2的正整数被称为windy数. windy想知道, 在A和B之间,包括A和B,总共有多少个windy数? 输入输出格式 输 ...
- [USACO10MAR]伟大的奶牛聚集 BZOJ 1827 树形dp+dfs
题目描述 Bessie is planning the annual Great Cow Gathering for cows all across the country and, of cours ...
- js 伪数组 arguments
/* 定义一个函数,如果不确定用户是否传入了参数, arguments可以获取到函数传入了多少个参数 和每个参数的值 */ /* 定义 */ function f1() { //获取的是函数在调用的时 ...
- C# 获取类中属性注释值
转 http://bbs.csdn.net/topics/350019800 PropertyInfo[] peroperties = typeof(TEST).GetProperties(Bindi ...
- Hadoop Hive概念学习系列之什么是Hive?
参考 <Hadoop大数据分析与挖掘实战>的在线电子书阅读 http://yuedu.baidu.com/ebook/d128cf8e33687e21 ...