Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL Illegal Character

Here is my code:

HttpClient client = new DefaultHttpClient();
            client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android");
            HttpGet request = new HttpGet();
            request.setHeader("Content-Type", "text/plain; charset=utf-8");
            Log.d("URL", convertURL(URL));
            request.setURI(new URI(URL));
            HttpResponse response = client.execute(request);
            bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer stringBuffer = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");

I don't know which error in my URL:

http://localhost/CyborgService/chatservice.php?action=recive_game&nick_sender=mkdarkness&pass=MV030595&date_last=2012-11-18 09:46:37&id_game=1

I have already used a function to convert URL, but has not worked. But, if I trying open this URL in my Browser, it opens successfully.

Here is my error:

11-18 21:46:37.766: E/GetHttp(823): java.net.URISyntaxException: Illegal character in query at index 127: http://192.168.0.182/CyborgService/chatservice.php?action=recive_game&nick_sender=mkdarkness&pass=MV030595&date_last=2012-11-18 09:46:37&id_game=1
like image 677
Marcos Bergamo Avatar asked Dec 16 '25 22:12

Marcos Bergamo


2 Answers

There is a space in your URL, in position 127. The date is generated as "date_last=2012-11-18 09:46:37", which causes an error when opening the URL.

Spaces are not formally accepted in URLs, although your browser will happily convert it to "%20" or to "+", both valid representations of a space in a URL. You should escape all characters: you can replace space with "+" or just pass the String through URLEncoder and be done with it.

To use URLEncoder see e.g. this question: encode with URLEncoder only parameter values, not the full URL. Or use one of the constructors for URI which have a few parameters, not a single one. You are not showing the code that constructs the URL so I cannot comment on it explicitly. But if you have a map of parameters parameterMap it would be something like:

String url = baseUrl + "?";
for (String key : parameterMap.keys())
{
  String value = parameterMap.get(key);
  String encoded = URLEncoder.encode(value, "UTF-8");
  url += key + "&" + encoded;
}

Some other day we can talk about why Java requires to set the encoding and then requires that the encoding be "UTF-8", instead of just using "UTF-8" as the default encoding, but for now this code should do the trick.

like image 132
alexfernandez Avatar answered Dec 19 '25 13:12

alexfernandez


There is a whitespace character:

...2012-11-18 09:46:37... (at index 127, just like the error message says).

Try replacing it with %20

like image 22
jlordo Avatar answered Dec 19 '25 12:12

jlordo