HTTP URL Address Encoding in Java

前端 未结 26 1770
醉酒成梦
醉酒成梦 2020-11-22 01:35

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 encod

26条回答
  •  滥情空心
    2020-11-22 02:10

    Please be warned that most of the answers above are INCORRECT.

    The URLEncoder class, despite is name, is NOT what needs to be here. It's unfortunate that Sun named this class so annoyingly. URLEncoder is meant for passing data as parameters, not for encoding the URL itself.

    In other words, "http://search.barnesandnoble.com/booksearch/first book.pdf" is the URL. Parameters would be, for example, "http://search.barnesandnoble.com/booksearch/first book.pdf?parameter1=this¶m2=that". The parameters are what you would use URLEncoder for.

    The following two examples highlights the differences between the two.

    The following produces the wrong parameters, according to the HTTP standard. Note the ampersand (&) and plus (+) are encoded incorrectly.

    uri = new URI("http", null, "www.google.com", 80, 
    "/help/me/book name+me/", "MY CRZY QUERY! +&+ :)", null);
    
    // URI: http://www.google.com:80/help/me/book%20name+me/?MY%20CRZY%20QUERY!%20+&+%20:)
    

    The following will produce the correct parameters, with the query properly encoded. Note the spaces, ampersands, and plus marks.

    uri = new URI("http", null, "www.google.com", 80, "/help/me/book name+me/", URLEncoder.encode("MY CRZY QUERY! +&+ :)", "UTF-8"), null);
    
    // URI: http://www.google.com:80/help/me/book%20name+me/?MY+CRZY+QUERY%2521+%252B%2526%252B+%253A%2529
    

提交回复
热议问题