Zeroth Tech
Zeroth Tech

Reputation: 75

Illegal character in query in URL Connection

I am trying to get JSON data from an URL and I have checked the URL via my browser, it's showing me valid JSON data whilst, if I do the same, I am getting the following error:

Illegal character in query at index 47: http://bangladeshelections.org/candidate?where={

index 47 is the first braces after where.

I have tried the following code to get the URL

here, value is an array from the previous activity.

        District = value[0];
        Municipality = value[1];
        Type = value[2];
        Ward = value[3];
        url_all_products = url_all_products + "District\":\""+District+"\",\"Municipality\":\""+
                Municipality+"\",\"Type\":\""+Type+"\",\"Ward\":\""+Ward+"\"}";
        Log.i("Monkey", url_all_products.charAt(47) + "bulls");
        new LoadAllProducts(getApplicationContext()).execute();

The following code's are I am using to get JSON data in an Async Thread

  URL url = new URL(url_all_products);
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url_all_products));
            HttpResponse response = client.execute(request);
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line="";

            while ((line = in.readLine()) != null) {
                sb.append(line);
                break;
            }
            in.close();
            return sb.toString();

Thank you.

Upvotes: 0

Views: 1341

Answers (1)

pvg
pvg

Reputation: 2729

Your query string uses illegal characters - the easiest way to avoid this without external libraries is to use java.net.URI to construct your URL from its components. It includes a constructor that accepts a query string and will perform the proper encoding for you. For example to encode:

http://host.com/path?query=queryparam#fragment

new URI("http", "host.com", "/path/", "query=queryparam", "fragment").toURL();

See the docs at

http://docs.oracle.com/javase/6/docs/api/java/net/URI.html

Upvotes: 1

Related Questions