java url连接被拒绝,Java的URL/URI无法正确解析以?开头的链接.(审讯点)

I'm trying to resolve a relative link that starts with a question mark ? using Java's URL or URI classes.

HTML example:

Test XYZ

Code examples (from Scala REPL):

import java.net._

scala> new URL(new URL("http://abc.com.br/index.php?hello=world"), "?test=xyz").toExternalForm()

res30: String = http://abc.com.br/?test=xyz

scala> (new URI("http://abc.com.br/index.php?hello=world")).resolve("?test=xyz").toString

res31: java.net.URI = http://abc.com.br/?test=xyz

The problem is that browsers (tested on Chrome, Firefox and Safari) output the following URL instead: http://abc.com.br/index.php?hello=world. It doesn't discard the path "index.php". It just replaces the query string part.

And it seems that browsers are just following the especification as explained in https://stackoverflow.com/a/7872230/40876.

Jsoup library makes the same "mistake" when we use element.absUrl("href") as it also depends on java's URL resolving.

So what's up with java's URL/URI resolving relative paths? Is it wrong/incomplete?

How to make it behave the same as the browsers implementation?

解决方案

This will work just fine:

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

String base = "http://abc.com.br/index.php?hello=world";

String relative = "?test=xyz";

System.out.println(new URL(new URL(base), relative).toExternalForm());

// http://abc.com.br/?test=xyz

System.out.println((new URI(base)).resolve(relative).toString());

// http://abc.com.br/?test=xyz

System.out.println(org.apache.http.client.utils.URIUtils.resolve(new URI(base), relative).toString());

// http://abc.com.br/index.php?test=xyz

}

URIUtils live in org.apache.httpcomponents:httpclient version 4.0 or higher.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值