I need to encode a URL using HTTP GET request in Blackberry. Can any one help me find how do I achieve this.
Asked
Active
Viewed 5,783 times
4 Answers
18
Whyt don't you use RIM's URLEncodedPostData?
private String encodeUrl(String hsURL) {
URLEncodedPostData urlEncoder = new URLEncodedPostData("UTF-8", false);
urlEncoder.setData(hsURL);
hsURL = urlEncoder.toString();
return hsURL;
}

Maksym Gontar
- 22,765
- 10
- 78
- 114
-
Great solution but not portable. Given he wants to run his software on a different mobile, he'll be asking the same question again. Best is to steer clear of classes which only run on one platform. – Toad Jul 31 '09 at 09:24
-
Can't tell for sure... In this case you're right, cause it's not platform dependent functionality. But still simple is good, implement it when they ask you. – Maksym Gontar Jul 31 '09 at 09:35
-
4He doesn't actually say he's writing cross-platform mobile code so in this case I'd side with coldice - it seems safer to me (less likely to introduce bugs) to use a native API over a homebrew approach. – Marc Novakowski Aug 03 '09 at 23:03
-
Maybe I'm misunderstanding the question here, but I don't think this answer does what the question asks, at all. `URLEncodedPostData` is meant for URL encoding sets of **POST** params (key/value pairs), to be written as content bytes in a `POST` request. It looks to me (and to a couple other answers here) that the OP is asking to encode the URL itself. For example, `http://maps.google.com/?addr=123 Main St, New York, NY` -> `http://maps.google.com/?addr=123+Main+St,+New+York,+NY`. This doesn't do that. – Nate Feb 13 '13 at 08:18
-
I am not able to get a proper URL encoded string from this solution : here is my link https://maps.google.com/maps?saddr=HD5&DT4 8TA – AK Joshi Mar 28 '13 at 11:05
8
here you go ;^)
public static String URLencode(String s)
{
if (s!=null) {
StringBuffer tmp = new StringBuffer();
int i=0;
try {
while (true) {
int b = (int)s.charAt(i++);
if ((b>=0x30 && b<=0x39) || (b>=0x41 && b<=0x5A) || (b>=0x61 && b<=0x7A)) {
tmp.append((char)b);
}
else {
tmp.append("%");
if (b <= 0xf) tmp.append("0");
tmp.append(Integer.toHexString(b));
}
}
}
catch (Exception e) {}
return tmp.toString();
}
return null;
}

Toad
- 15,593
- 16
- 82
- 128
3
the reply using "URLEncodedPostData" above is incorrect. Corrected sample:
public static String encodeUrl(Hashtable params)
{
URLEncodedPostData urlEncoder = new URLEncodedPostData("UTF-8", false);
Enumeration keys = params.keys();
while (keys.hasMoreElements()) {
String name = (String) keys.nextElement();
String value = (String) params.get(name);
urlEncoder.append(name, value);
}
String encoded = urlEncoder.toString();
return encoded;
}
Cheers!