类urlencoder 和 类urldecoder
web设计者面临的众多难题之一便是怎样处理不同操作系统间的差异性。这些差异性能引起url方面的问题:例如,一些操作系统允许文件名中含有空格符,有些又不允许。大多数操作系统不会认为文件名中含有符号“#”会有什么特殊含义;但是在一个url中,符号“#”表示该文件名已经结束,后面会紧跟一个fragment(部分)标识符。其他的特殊字符,非字母数字字符集,它们在url或另一个操作系统上都有其特殊的含义,表述着相似的问题。为了解决这些问题,我们在url中使用的字符就必须是一个ascii字符集的固定字集中的元素,具体如下:
1.大写字母a-z
2.小写字母a-z
3.数字 0-9
4.标点符 - _ . ! ~ * ' (和 ,)
版权声明:任何获得matrix授权的网站,转载时请务必保留以下作者信息和链接
作者:elliotte rusty;leo173(作者的blog:http://blog.matrix.org.cn/page/leo173)
原文:http://www.onjava.com/pub/a/onjava/excerpt/jvntwkprg_3e/index.html
译文:http://www.matrix.org.cn/resource/article/44/44187_urlencoder+urldecoder.html
关键字:urls,uris,proxies,passwords
诸如字符: / & ? @ # ; $ + = 和 %也可以被使用,但是它们各有其特殊的用途,如果一个文件名包括了这些字符( / & ? @ # ; $ + = %),这些字符和所有其他字符就应该被编码。
编码过程非常简单,任何字符只要不是ascii码数字,字母,或者前面提到的标点符,它们都将被转换成字节形式,每个字节都写成这种形式:一个“%”
后面跟着两位16进制的数值。空格是一个特殊情况,因为它们太平常了。它除了被编码成“%20”以外,还能编码为一个“+”。加号(+)本身被编码为%2b。当/ # = & 和?作为名字的一部分来使用时,而不是作为url部分之间的分隔符来使用时,它们都应该被编码。
warning这种策略在存在大量字符集的异构环境中效果不甚理想。例如:在u.s. windows 系统中, é 被编码为 %e9. 在 u.s. mac中被编码为%8e。这种不确定性的存在是现存的uri的一个明显的不足。所以在将来uri的规范当中应该通过国际资源标识符(iris)进行改善。
类url并不自动执行编码或解码工作。你能生成一个url对象,它可以包括非法的ascii和非ascii字符和/或%xx。当用方法getpath() 和toexternalform( ) 作为输出方法时,这种字符和转移符不会自动编码或解码。你应对被用来生成一个url对象的字符串繁荣对象负责,确保所有字符都会被恰当地编码。
幸运的是,java提供了一个类urlencoder把string编码成这种形式。java1.2增加了一个类urldecoder它能以这种形式解码string。这两个类都不用初始化
public class urldecoder extends object
public class urlencoder extends object
public static string encode(string s, string encoding)
throws unsupportedencodingexception
import java.net.urlencoder;
import java.io.unsupportedencodingexception;
public class encodertest {
public static void main(string[] args) {
try {
system.out.println(urlencoder.encode("this string has spaces",
"utf-8"));
system.out.println(urlencoder.encode("this*string*has*asterisks",
"utf-8"));
system.out.println(urlencoder.encode("this%string%has%percent%signs",
"utf-8"));
system.out.println(urlencoder.encode("this+string+has+pluses",
"utf-8"));
system.out.println(urlencoder.encode("this/string/has/slashes",
"utf-8"));
system.out.println(urlencoder.encode("this\"string\"has\"quote\"marks",
"utf-8"));
system.out.println(urlencoder.encode("this:string:has:colons",
"utf-8"));
system.out.println(urlencoder.encode("this~string~has~tildes",
"utf-8"));
system.out.println(urlencoder.encode("this(string)has(parentheses)",
"utf-8"));
system.out.println(urlencoder.encode("this.string.has.periods",
"utf-8"));
system.out.println(urlencoder.encode("this=string=has=equals=signs",
"utf-8"));
system.out.println(urlencoder.encode("this&string&has&ersands",
"utf-8"));
system.out.println(urlencoder.encode("thiséstringéhasé
non-ascii characters", "utf-8"));
}
catch (unsupportedencodingexception ex) {
throw new runtimeexception("broken vm does not support utf-8");
}
}
}
% javac -encoding utf8 encodertest
% java encodertest
this+string+has+spaces
this*string*has*asterisks
this%25string%25has%25percent%25signs
this%2bstring%2bhas%2bpluses
this%2fstring%2fhas%2fslashes
this%22string%22has%22quote%22marks
this%3astring%3ahas%3acolons
this%7estring%7ehas%7etildes
this%28string%29has%28parentheses%29
this.string.has.periods
this%3dstring%3dhas%3dequals%3dsigns
this%26string%26has%26ampersands
this%c3%a9string%c3%a9has%c3%a9non-ascii+characters
pg=q&kl=xx&stype=stext&q=+"java+i/o"&search.x=38&search.y=3
string query = urlencoder.encode(
"pg=q&kl=xx&stype=stext&q=+\"java+i/o\"&search.x=38&search.y=3");
system.out.println(query);
pg%3dq%26kl%3dxx%26stype%3dstext%26q%3d%2b%22java%2bi%2fo%22%26search
.x%3d38%26search.y%3d3
string query = urlencoder.encode("pg");
query += "=";
query += urlencoder.encode("q");
query += "&";
query += urlencoder.encode("kl");
query += "=";
query += urlencoder.encode("xx");
query += "&";
query += urlencoder.encode("stype");
query += "=";
query += urlencoder.encode("stext");
query += "&";
query += urlencoder.encode("q");
query += "=";
query += urlencoder.encode("\"java i/o\"");
query += "&";
query += urlencoder.encode("search.x");
query += "=";
query += urlencoder.encode("38");
query += "&";
query += urlencoder.encode("search.y");
query += "=";
query += urlencoder.encode("3");
system.out.println(query);
pg=q&kl=xx&stype=stext&q=%2b%22java+i%2fo%22&search.x=38&search.y=3
package com.macfaq.net;
import java.net.urlencoder;
import java.io.unsupportedencodingexception;
public class querystring {
private stringbuffer query = new stringbuffer( );
public querystring(string name, string value) {
encode(name, value);
}
public synchronized void add(string name, string value) {
query.append('&');
encode(name, value);
}
private synchronized void encode(string name, string value) {
try {
query.append(urlencoder.encode(name, "utf-8"));
query.append('=');
query.append(urlencoder.encode(value, "utf-8"));
}
catch (unsupportedencodingexception ex) {
throw new runtimeexception("broken vm does not support utf-8");
}
}
public string getquery( ) {
return query.tostring( );
}
public string tostring( ) {
return getquery( );
}
}
querystring qs = new querystring("pg", "q");
qs.add("kl", "xx");
qs.add("stype", "stext");
qs.add("q", "+\"java i/o\"");
qs.add("search.x", "38");
qs.add("search.y", "3");
string url = "http://www.altavista.com/cgi-bin/query?" + qs;
system.out.println(url);
public static string decode(string s) throws exception
public static string decode(string s, string encoding) // java 1.4
throws unsupportedencodingexception
string input = "http://www.altavista.com/cgi-bin/" +
"query?pg=q&kl=xx&stype=stext&q=%2b%22java+i%2fo%22&search.x=38&search.y=3";
try {
string output = urldecoder.decode(input, "utf-8");
system.out.println(output);
}
uri voice = new uri("tel:+1-800-9988-9938");
uri web = new uri("http://www.xml.com/pub/a/2003/09/17/stax.html#id=_hbc");
uri book = new uri("urn:isbn:1-565-92870-9");
uri absolute = new uri("http", "//www.ibiblio.org" , null);
uri relative = new uri(null, "/javafaq/index.shtml", "today");
uri today= new uri("http", "www.ibiblio.org", "/javafaq/index.html", "today");
produces the uri http://www.ibiblio.org/javafaq/index.html#today
uri today= new uri("http", "www.ibiblio.org", "/javafaq/index.html",
"referrer=.net&date=2004-08-23", "today");
uri styles = new uri("ftp", "anonymous:elharo@metalab.unc.edu",
"ftp.oreilly.com", 21, "/pub/stylesheet", null, null);
uri styles = uri.create(
"ftp://anonymous:elharo%40metalab.unc.edu@ftp.oreilly.com:
21/pub/stylesheet");
scheme:scheme-specific-part:fragment
public string getscheme( )
public string getschemespecificpart( )
public string getrawschemespecificpart( )
public string getfragment( )
public string getrawfragment( )
public boolean isabsolute( )
public boolean isopaque( )
public string getauthority( )
public string getfragment( )
public string gethost( )
public string getpath( )
public string getport( )
public string getquery( )
public string getuserinfo( )
public string getrawauthority( )
public string getrawfragment( )
public string getrawpath( )
public string getrawquery( )
public string getrawuserinfo( )
public uri parseserverauthority( ) throws urisyntaxexception
import java.net.*;
public class urisplitter {
public static void main(string args[]) {
for (int i = 0; i < args.length; i++) {
try {
uri u = new uri(args[i]);
system.out.println("the uri is " + u);
if (u.isopaque( )) {
system.out.println("this is an opaque uri.");
system.out.println("the scheme is " + u.getscheme( ));
system.out.println("the scheme specific part is "
+ u.getschemespecificpart( ));
system.out.println("the fragment id is " + u.getfragment( ));
}
else {
system.out.println("this is a hierarchical uri.");
system.out.println("the scheme is " + u.getscheme( ));
try {
u = u.parseserverauthority( );
system.out.println("the host is " + u.getuserinfo( ));
system.out.println("the user info is " + u.getuserinfo( ));
system.out.println("the port is " + u.getport( ));
}
catch (urisyntaxexception ex) {
// must be a registry based authority
system.out.println("the authority is " + u.getauthority( ));
}
system.out.println("the path is " + u.getpath( ));
system.out.println("the query string is " + u.getquery( ));
system.out.println("the fragment id is " + u.getfragment( ));
} // end else
} // end try
catch (urisyntaxexception ex) {
system.err.println(args[i] + " does not seem to be a uri.");
}
system.out.println( );
} // end for
} // end main
} // end urisplitter
% java urisplitter tel:+1-800-9988-9938
\http://www.xml.com/pub/a/2003/09/17/stax.html#id=_hbc \urn:isbn:1-565-92870-9
the uri is tel:+1-800-9988-9938
this is an opaque uri.
the scheme is tel
the scheme specific part is +1-800-9988-9938
the fragment id is null
the uri is http://www.xml.com/pub/a/2003/09/17/stax.html#id=_hbc
this is a hierarchical uri.
the scheme is http
the host is null
the user info is null
the port is -1
the path is /pub/a/2003/09/17/stax.html
the query string is null
the fragment id is id=_hbc
the uri is urn:isbn:1-565-92870-9
this is an opaque uri.
the scheme is urn
the scheme specific part is isbn:1-565-92870-9
the fragment id is null
uri absolute = new uri("http://www.example.com/");
uri relative = new uri("images/logo.png");
uri resolved = absolute.resolve(relative);
uri top = new uri("javafaq/books/");
uri relative = new uri("jnp3/examples/07/index.html");
uri resolved = top.resolve(relative);
uri absolute = new uri("http://www.example.com/");
uri resolved = absolute.resolve("images/logo.png");
uri top = new uri("javafaq/books/");
resolved = top.resolve("jnp3/examples/07/index.html");
public uri relativize(uri uri)
uri absolute = new uri("http://www.example.com/images/logo.png");
uri top = new uri("http://www.example.com/");
uri relative = top.relativize(absolute);
% java -dhttp.proxyhost=192.168.254.254 -dhttp.proxyport=9000
com.domain.program
system.setproperty("http.proxyhost", "192.168.254.254");
system.setproperty("http.proxyport", "9000");
system.setproperty("http.nonproxyhosts", "java.oreilly.comxml.oreilly.com");
% java -dhttp.proxyhost=192.168.254.254 -dhttp.nonproxyhosts=*.oreilly.com
com.domain.program
socketaddress address = new .netsocketaddress("proxy.example.com", 80);
proxy proxy = new proxy(proxy.type.http, address);
public abstract list<proxy> select(uri uri)
public void connectfailed(uri uri, socketaddress address, ioexception ex)
import java.net.*;
import java.util.*;
import java.io.*;
public class localproxyselector extends proxyselector {
private list failed = new arraylist( );
public list<proxy> select(uri uri) {
list<proxy> result = new arraylist<proxy>( );
if (failed.contains(uri)
"http".equalsignorecase(uri.getscheme( ))) {
result.add(proxy.no_proxy);
}
else {
socketaddress proxyaddress
= new .netsocketaddress( "proxy.example.com", 8000);
proxy proxy = new proxy(proxy.type.http, proxyaddress);
result.add(proxy);
}
return result;
}
public void connectfailed(uri uri, socketaddress address, ioexception ex) {
failed.add(uri);
}
}
proxyselector selector = new localproxyselector( ):
proxyselector.setdefault(selector);
<form name="search" action="http://www.google.com/search" method="get">
<input name="q" />
<input type="hidden" value="cafeconleche.org" name="domains" />
<input type="hidden" name="sitesearch" value="cafeconleche.org" />
<input type="hidden" name="sitesearch2" value="cafeconleche.org" />
<br />
<input type="image" height="22" width="55"
src="images/search_blue.gif" alt="search" border="0"
name="search-image" />
</form>
http://www.ibiblio.org/nywc/compositionsbycomposer.phtml?last=anderson
&first=beth&middle=
http://www.ibiblio.org/nywc/compositionsbycomposer.phtml?last=austin
&first=dorothea&middle=
http://www.ibiblio.org/nywc/compositionsbycomposer.phtml?last=bliss
&first=marilyn&middle=
http://www.ibiblio.org/nywc/compositionsbycomposer.phtml?last=hart
&first=jane&middle=smith
<form accept-charset="utf-8"
action="http://search.dmoz.org/cgi-bin/search" method="get">
<input size=30 name=search>
<input type=submit value="search">
<a href="http://search.dmoz.org/cgi-bin/search?a.x=0">
<small><i>advanced</i></small></a>
</form>
import com.macfaq.net.*;
import java.net.*;
import java.io.*;
public class dmoz {
public static void main(string[] args) {
string target = "";
for (int i = 0; i < args.length; i++) {
target += args[i] + " ";
}
target = target.trim( );
querystring query = new querystring("search", target);
try {
url u = new url("http://search.dmoz.org/cgi-bin/search?" + query);
inputstream in = new bufferedinputstream(u.openstream( ));
inputstreamreader thehtml = new inputstreamreader(in);
int c;
while ((c = thehtml.read( )) != -1) {
system.out.print((char) c);
}
}
catch (malformedurlexception ex) {
system.err.println(ex);
}
catch (ioexception ex) {
system.err.println(ex);
}
}
}
public static void setdefault(authenticator a)
authenticator.setdefault(new dialogauthenticator( ));
public static passwordauthentication requestpasswordauthentication(
.netaddress address, int port, string protocol, string prompt, string scheme)
throws securityexception
protected passwordauthentication getpasswordauthentication( )
protected final .netaddress getrequestingsite( )
protected final int getrequestingport( )
protected final string getrequestingprotocol( )
protected final string getrequestingprompt( )
protected final string getrequestingscheme( )
protected final string getrequestinghost( ) // java 1.4
protected final string getrequestingurl( ) // java 1.5
protected authenticator.requestortype getrequestortype( )
public passwordauthentication(string username, char[] password)
public string getusername( )
public char[] getpassword( )
public class jpasswordfield extends jtextfield
public char[] getpassword( )
package com.macfaq.net;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class dialogauthenticator extends authenticator {
private jdialog passworddialog;
private jlabel mainlabel
= new jlabel("please enter username and password: ");
private jlabel userlabel = new jlabel("username: ");
private jlabel passwordlabel = new jlabel("password: ");
private jtextfield usernamefield = new jtextfield(20);
private jpasswordfield passwordfield = new jpasswordfield(20);
private jbutton okbutton = new jbutton("ok");
private jbutton cancelbutton = new jbutton("cancel");
public dialogauthenticator( ) {
this("", new jframe( ));
}
public dialogauthenticator(string username) {
this(username, new jframe( ));
}
public dialogauthenticator(jframe parent) {
this("", parent);
}
public dialogauthenticator(string username, jframe parent) {
this.passworddialog = new jdialog(parent, true);
container pane = passworddialog.getcontentpane( );
pane.setlayout(new gridlayout(4, 1));
pane.add(mainlabel);
jpanel p2 = new jpanel( );
p2.add(userlabel);
p2.add(usernamefield);
usernamefield.settext(username);
pane.add(p2);
jpanel p3 = new jpanel( );
p3.add(passwordlabel);
p3.add(passwordfield);
pane.add(p3);
jpanel p4 = new jpanel( );
p4.add(okbutton);
p4.add(cancelbutton);
pane.add(p4);
passworddialog.pack( );
actionlistener al = new okresponse( );
okbutton.addactionlistener(al);
usernamefield.addactionlistener(al);
passwordfield.addactionlistener(al);
cancelbutton.addactionlistener(new cancelresponse( ));
}
private void show( ) {
string prompt = this.getrequestingprompt( );
if (prompt == null) {
string site = this.getrequestingsite( ).gethostname( );
string protocol = this.getrequestingprotocol( );
int port = this.getrequestingport( );
if (site != null & protocol != null) {
prompt = protocol + "://" + site;
if (port > 0) prompt += ":" + port;
}
else {
prompt = "";
}
}
mainlabel.settext("please enter username and password for "
+ prompt + ": ");
passworddialog.pack( );
passworddialog.show( );
}
passwordauthentication response = null;
class okresponse implements actionlistener {
public void actionperformed(actionevent e) {
passworddialog.hide( );
// the password is returned as an array of
// chars for security reasons.
char[] password = passwordfield.getpassword( );
string username = usernamefield.gettext( );
// erase the password in case this is used again.
passwordfield.settext("");
response = new passwordauthentication(username, password);
}
}
class cancelresponse implements actionlistener {
public void actionperformed(actionevent e) {
passworddialog.hide( );
// erase the password in case this is used again.
passwordfield.settext("");
response = null;
}
}
public passwordauthentication getpasswordauthentication( ) {
this.show( );
return this.response;
}
}
import java.net.*;
import java.io.*;
import com.macfaq.net.dialogauthenticator;
public class securesourceviewer {
public static void main (string args[]) {
authenticator.setdefault(new dialogauthenticator( ));
for (int i = 0; i < args.length; i++) {
try {
//open the url for reading
url u = new url(args[i]);
inputstream in = u.openstream( );
// buffer the input to increase performance
in = new bufferedinputstream(in);
// chain the inputstream to a reader
reader r = new inputstreamreader(in);
int c;
while ((c = r.read( )) != -1) {
system.out.print((char) c);
}
}
catch (malformedurlexception ex) {
system.err.println(args[0] + " is not a parseable url");
}
catch (ioexception ex) {
system.err.println(ex);
}
// print a blank line to separate pages
system.out.println( );
} // end for
// since we used the awt, we have to explicitly exit.
system.exit(0);
} // end main
} // end securesourceviewer
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器