5

I have a url encoded string that is returned from an API I am using. I want to do something request.getParameter("paramname") on the string. What I'm looking for is something like str.request.getParameter("paramname"). There's gotta be something like this right?

clarification the api returns something like: name1=val1&name2=val2&name3=val3

I know i could do a split on "&" and then go through each element but that seems stupid. Please advise. Thanks!

Lye
  • 61
  • 1
  • 4
  • "There's gotta be something like this right?" unfortunately, no. Split and again. – Nishant Mar 22 '11 at 18:28
  • Probable duplicate with: http://stackoverflow.com/questions/1667278/parsing-query-strings-in-java . There are a couple of very good answers in there. – Aleadam Mar 22 '11 at 21:18

2 Answers2

2

Use URLEncodedUtils from Apache httpclient library.

API : http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html

You will have to call this method to get name value pairs:

static List<NameValuePair>  parse(HttpEntity entity)
          Returns a list of NameValuePairs as parsed from an HttpEntity.
Shamit Verma
  • 3,839
  • 23
  • 22
0

See this question

One answer there:

import org.eclipse.jetty.util.*;

MultiMap<String> params = new MultiMap<String>();
UrlEncoded.decodeTo("foo=bar&bla=blub", params, "UTF-8");

assert params.getString("foo").equals("bar");
assert params.getString("bla").equals("blub");
Community
  • 1
  • 1
moritz
  • 5,094
  • 1
  • 26
  • 33
  • that question doesn't seem to address my problem. I said I didn't want to do the splits. – Lye Mar 22 '11 at 18:30
  • basically you're saying, "no". – Nishant Mar 22 '11 at 18:30
  • There are a lot of answers, as for example using the apache libs or the jetty libs, then they will split and encode for you. – moritz Mar 22 '11 at 18:33
  • uh oh, yeah you're right. there is this one can look into: http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html#parse%28org.apache.http.HttpEntity%29 – Nishant Mar 22 '11 at 18:36
  • apparently that package doesn't exist? – Lye Mar 22 '11 at 18:43
  • [javadoc](http://download.eclipse.org/jetty/stable-7/apidocs/org/eclipse/jetty/util/UrlEncoded.html) it belongs to the eclipse jetty project, in the jdk itself there is no such class, you have to use jetty client or server libs. – moritz Mar 22 '11 at 18:46