Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Convert String to valid URI object

I am trying to get a java.net.URI object from a String. The string has some characters which will need to be replaced by their percentage escape sequences. But when I use URLEncoder to encode the String with UTF-8 encoding, even the / are replaced with their escape sequences.

How can I get a valid encoded URL from a String object?

http://www.google.com?q=a b gives http%3A%2F%2www.google.com... whereas I want the output to be http://www.google.com?q=a%20b

Can someone please tell me how to achieve this.

I am trying to do this in an Android app. So I have access to a limited number of libraries.

like image 216
lostInTransit Avatar asked Feb 21 '09 15:02

lostInTransit


People also ask

Is URI a string?

A URI is a string containing characters that identify a physical or logical resource.

What is URI parsing?

URL Parsing. The URL parsing functions focus on splitting a URL string into its components, or on combining URL components into a URL string.

What is a URI in Java?

A URI is a uniform resource identifier while a URL is a uniform resource locator. Hence every URL is a URI, abstractly speaking, but not every URI is a URL. This is because there is another subcategory of URIs, uniform resource names (URNs), which name resources but do not specify how to locate them.

How do you parse a space in a URL?

Spaces are not allowed in URLs. They should be replaced by the string %20. In the query string part of the URL, %20 can be abbreviated using a plus sign (+).


2 Answers

You might try: org.apache.commons.httpclient.util.URIUtil.encodeQuery in Apache commons-httpclient project

Like this (see URIUtil):

URIUtil.encodeQuery("http://www.google.com?q=a b") 

will become:

http://www.google.com?q=a%20b 

You can of course do it yourself, but URI parsing can get pretty messy...

like image 69
Hans Doggen Avatar answered Sep 20 '22 19:09

Hans Doggen


Android has always had the Uri class as part of the SDK: http://developer.android.com/reference/android/net/Uri.html

You can simply do something like:

String requestURL = String.format("http://www.example.com/?a=%s&b=%s", Uri.encode("foo bar"), Uri.encode("100% fubar'd")); 
like image 27
bensnider Avatar answered Sep 22 '22 19:09

bensnider