How to parse URL strings in Java

I tend to use apache httpclient as my preferred java http client. I hit an error with invalid symbols such as the space character in this url:

val urlString = ", NY"

val cm = new ThreadSafeClientConnManager()
val client = new DefaultHttpClient(cm)
val httpRequest = new HttpGet(urlString)

java.lang.IllegalArgumentException: Illegal character in query at index 38:, NY
at org.apache.http.client.methods.HttpGet.(

My first attempt would be to use, "UTF-8")
res4: java.lang.String =

But this doesn’t work, it’s only for forms and it tries to encode the entire url string.

Our goal is to convert just the param part of the url from “, NY” to “”

The trick is to construct a URL object so we can get the separate components and then create a URI object from these components:

val urlString = ", NY"
val url = new
val uri = new, url.getAuthority, url.getPath, url.getQuery, null)
val httpRequest = new HttpGet(uri)
httpRequest: org.apache.http.client.methods.HttpGet = org.apache.http.client.methods.HttpGet@15ec2337

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s