java 怎么对url解码_如何在Java中进行URL解码?

在Java中,我想将其转换为:

https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type

对此:

https://mywebsite/docs/english/site/mybook.do&request_type

这是我到目前为止的内容:

class StringUTF

{

public static void main(String[] args)

{

try{

String url =

"https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do" +

"%3Frequest_type%3D%26type%3Dprivate";

System.out.println(url+"Hello World!------->" +

new String(url.getBytes("UTF-8"),"ASCII"));

}

catch(Exception E){

}

}

}

但这行不通。 这些%3A和%2F格式叫什么?如何转换它们?

#1楼

这已经被回答过 (尽管这个问题是第一个!):

“您应该使用java.net.URI来执行此操作,因为URLDecoder类会进行x-www-form-urlencoded解码,这是错误的(尽管名称,它用于表单数据)。”

基本上:

String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type";

System.out.println(new java.net.URI(url).getPath());

会给你:

https://mywebsite/docs/english/site/mybook.do?request_type

#2楼

import java.io.UnsupportedEncodingException;

import java.net.URISyntaxException;

public class URLDecoding {

String decoded = "";

public String decodeMethod(String url) throws UnsupportedEncodingException

{

decoded = java.net.URLDecoder.decode(url, "UTF-8");

return decoded;

//"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."

}

public String getPathMethod(String url) throws URISyntaxException

{

decoded = new java.net.URI(url).getPath();

return decoded;

}

public static void main(String[] args) throws UnsupportedEncodingException, URISyntaxException

{

System.out.println(" Here is your Decoded url with decode method : "+ new URLDecoding().decodeMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type"));

System.out.println("Here is your Decoded url with getPath method : "+ new URLDecoding().getPathMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest"));

}

}

您可以明智地选择方法:)

#3楼

String decodedUrl = new URLCodec().decode(url);

默认字符集为UTF-8

#4楼

try {

String result = URLDecoder.decode(urlString, "UTF-8");

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

#5楼

public String decodeString(String URL)

{

String urlString="";

try {

urlString = URLDecoder.decode(URL,"UTF-8");

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

}

return urlString;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值