user3225075
user3225075

Reputation: 373

encode url to fetch JSON data

I am trying to fetch json data from remote server. Everything works fine just when a two character string is passed my app gets force stopped. How to encode the url to prevent this error

here is how am trying to fetch json values

  jsonobject = JSONfunctions.getJSONfromURL("http://www.example.com/index.php?sutyp="+sutyp);

If i pass "Hello" through sutyp there is no error but if i pass "Hello World" app force stops

How do I encode the url to prevent this. Any suggestions would be of great help

Upvotes: 1

Views: 158

Answers (2)

Yash Sampat
Yash Sampat

Reputation: 30611

You need to use the android.net.Uri class:

String url = Uri.parse("http://www.example.com/index.php")
                .buildUpon()
                .appendQueryParameter("sutyp", sutyp)
                .build()
                .toString();

jsonobject = JSONfunctions.getJSONfromURL(url);

From the docs:

Encodes characters in the given string as '%'-escaped octets using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes all other characters.

Upvotes: 1

peshkira
peshkira

Reputation: 6239

You could use URLEncoder.encode(string, "utf-8")

For example

String url = String.format("http://www.example.com/index.php?sutyp=%s", sutyp);
jsonobject = JSONfunctions.getJSONfromURL(URLEncoder.encode(url, "utf-8");

Here is a reference to the documentation

Upvotes: 1

Related Questions