Reputation: 119
I've got an android application that I'm attempting to use to pass some data to a webservice using HTTPGet. If I just construct the string using the JSONArray.toString() method, I end up with a URL that looks something like the following:
http://xxx.xx.xxx.xx/api?method=upload&args[deviceID]=123456789&args[data]=["{element1=93295352, element2=235235, element3=3523523}","{element1=93295352, element2=235235, element3=3523523}"]
This doesn't work because of the spaces and quotation marks in the URL. If I attampt to do something like the following:
JSONArray ja = new JSONArray();
// Add Data to JSONArray
String s = ja.toString();
// Add array to StringBuilder url
HTTPGet httpget = new HTTPGet(UrlEncoder.encode(url.toString()));
I get an error thrown because the entire URL gets encoded and ends up like this:
http%3A%2F%2Fxxx.xx.xxx.xx%2Fapi%3Fmethod%3Dupload%26args%5BdeviceID%5D%3D123456879%26args%5Bdata%5D%3D%5B%22%7Belement1%3D915156028000%2C+element2%3D1651651%2C+element3%3D489461%7D%22%2C%22
Obviously, this isn't what I'm looking for, and there's got to be a better solution than searching/replacing all the necessary characters in the JSONArray portion of that url, though I suppose doing it that way wouldn't be a huge hassle since I'm only worried about quotation and space characters.
Note that manually pasting this into my browser returned the results I expect:
http://xxx.xx.xxx.xx/api?method=upload&args[deviceID]=123456789&args[data]=[%22{element1=915156028000,%20element2=0.0,%20element3=2.297444}%22,%22{element1=915156055000,%20element2=0.0,%20element3=2.2974419999999998}%22]
Upvotes: 2
Views: 20756
Reputation: 719259
You need to URL encode just the query argument value; for example
JSONArray ja = new JSONArray();
// Add Data to JSONArray
String s = UrlEncoder.encode(ja.toString());
// Add string to StringBuilder url
HTTPGet httpget = new HTTPGet(url.toString());
The other thing that you need to be aware of is that there are practical limits on the length of a URL. These limits vary from one implementation to another (browser, server, proxy, HTTP client library, etc). In some cases, it is as low as 2k bytes, IIRC.
FOLLOW UP
If I want to do the same thing using POST instead, do I end up having to encode the data in the same manner?
It depends.
+
characters.)Of course, one of the advantages of using POST data is that there is typically no limit on the size of the arguments you can send.
Upvotes: 6