在Java中,我想將其轉換爲: java
https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type
對此: web
https://mywebsite/docs/english/site/mybook.do&request_type
這是我到目前爲止的內容: apache
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
格式叫什麼?如何轉換它們? this
這已經被回答過 (儘管這個問題是第一個!): url
「您應該使用java.net.URI來執行此操做,由於URLDecoder類會進行x-www-form-urlencoded解碼,這是錯誤的(儘管名稱,它用於表單數據)。」 spa
基本上: .net
String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type"; System.out.println(new java.net.URI(url).getPath());
會給你: code
https://mywebsite/docs/english/site/mybook.do?request_type
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")); } }
您能夠明智地選擇方法:) orm
我使用apache commons get
String decodedUrl = new URLCodec().decode(url);
默認字符集爲UTF-8
try { String result = URLDecoder.decode(urlString, "UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); }
public String decodeString(String URL) { String urlString=""; try { urlString = URLDecoder.decode(URL,"UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block } return urlString; }