java http编码,Java中的HTTP URL地址编码

在Java中,使用URLEncoder对HTTP URL进行编码时可能会遇到问题,因为URLEncoder主要针对HTML表单编码。要正确编码HTTP URL,可以使用java.net.URI类。通过URI类的构造函数,可以创建并编码URL,确保非法字符被适当地转义。例如,创建URI对象后,可以调用toASCIIString()方法得到正确的编码结果,将空格转换为%20。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

My Java standalone application gets a URL (which points to a file) from the user and I need to hit it and download it. The problem I am facing is that I am not able to encode the HTTP URL address properly...

Example:

URL: http://search.barnesandnoble.com/booksearch/first book.pdf

java.net.URLEncoder.encode(url.toString(), "ISO-8859-1");

returns me:

http%3A%2F%2Fsearch.barnesandnoble.com%2Fbooksearch%2Ffirst+book.pdf

But, what I want is

http://search.barnesandnoble.com/booksearch/first%20book.pdf

(space replaced by %20)

I guess URLEncoder is not designed to encode HTTP URLs... The JavaDoc says "Utility class for HTML form encoding"... Is there any other way to do this?

解决方案

The java.net.URI class can help; in the documentation of URL you find

Note, the URI class does perform escaping of its component fields in certain circumstances. The recommended way to manage the encoding and decoding of URLs is to use an URI

Use one of the constructors with more than one argument, like:

URI uri = new URI(

"http",

"search.barnesandnoble.com",

"/booksearch/first book.pdf",

null);

URL url = uri.toURL();

//or String request = uri.toString();

(the single-argument constructor of URI does NOT escape illegal characters)

Only illegal characters get escaped by above code - it does NOT escape non-ASCII characters (see fatih's comment).

The toASCIIString method can be used to get a String only with US-ASCII characters:

URI uri = new URI(

"http",

"search.barnesandnoble.com",

"/booksearch/é",

null);

String request = uri.toASCIIString();

For an URL with a query like http://www.google.com/ig/api?weather=São Paulo, use the 5-parameter version of the constructor:

URI uri = new URI(

"http",

"www.google.com",

"/ig/api",

"weather=São Paulo",

null);

String request = uri.toASCIIString();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值