Reputation: 12170
I'm writing an Android application that will fetch content from Internet. The URL consists of some query parameters with String values. The problem is when I'm trying to use a string value that contains some spaces it doesn't work. But, others work fine. This is the code below that I use to get content with get method.
URL url = new URL("http://www.example.com/fetch.php?title="+someStringValue);
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
while((temp=br.readLine())!=null){
data+=temp;
}
The problem is I cannot use a spaced string for the variable someStringValue
. I know that there are some encoding problems, but how can I resolve it? Also, what's the best way to read data data from a URL using GET method?
Upvotes: 0
Views: 791
Reputation: 121710
OK, so, before a common misconception makes it way in there...
URLEncoder
does not work.
URLEncoder
encodes data for application/x-www-form-urlencoded
data. And this is not what is used to escape URI query fragments. For one, the set of escaped characters is different; and of course there is the problem that this method encodes spaces with +
.
Here are three solutions...
Use the URI
constructor:
// Put title string UNESCAPED; the constructor will escape for you
final URL url = new URI("http", null, "www.example.com", -1, "/fecth.php",
"title=yourtitle", null).toURL();
If you are using Guava (15+) then you may use this class, which also does the job:
final Escaper escaper = UrlEscapers.urlPathSegmentEscaper();
final String escapedTitle = escaper.escape("yourtitlestring");
final URL url = new URL("http://www.example.com/fetch.php?title="
+ escapedTitle);
The bazooka to kill a fly: URI templates. Using this library:
final URITemplate template
= new URITemplate("http://www.example.com/fetch.php?title={title}");
final VariableMap varmap = VariableMap.newBuilder()
.addScalar("title", "yourtitlehere")
.build();
final URL url = template.toURL(varmap);
Upvotes: 3
Reputation: 9450
Edit :
fge is actually right, URLEncoder
will give you "+" instead of "%20" for spaces.
Since you are on android I recommend simple alternative :
URL url = new URL("http://www.example.comfetch.php?title=" +
Uri.encode(someStringValue));
Using Uri.encode
Upvotes: 3
Reputation: 296
You need to replace the spaces with the code "%20". URL encoding replaces a space with this code.
To read data I usually use the BufferedReader but like this:
URL url = new URL("URL");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String s, response = "";
while ((s = rd.readLine()) != null) {
response += s;
}
Upvotes: 1