Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpURLConnection with URL that contains space

I have a url that one of its params contains a space character. If I send it as is, using HttpURLConnection, this param passes wrongly.

If I manually replace the space with %20, it's working as expected so I was wondering if there is a cleaner way to do so though I was hoping that HttpURLConnection will do it automatically. Maybe there is a way that I missed?

When looking for this, I keep bumping into URLEncoder.Encode which is deprecated and I couldn't find any other way to do what I do except for encoding the whole URL, including the :// of the http.

Is there a clean way to do the replacement or should I do it manually?

url for example: http://www.domain.com?param1=name'last&param2=2014-31-10 11:40:00 param 1 contains ' and param2 contains both space and : but only the space makes the problem. This is why I don't understand why HttpUrlConnection is so sensitive for space only.

Thanks

like image 907
Amos Avatar asked Oct 31 '14 09:10

Amos


2 Answers

Try this way,hope this will help you to solve your problem.

URLEncoder : All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9') and characters '.', '-', '*', '_' are converted into their hexadecimal value prepended by '%'.

In URLEncoder class have two method :

1.encode(String url) : This method was deprecated in API level 1

String encodedUrl = URLEncoder.encode(url);

2.encode(String url, String charsetName) : Encodes url using the Charset named by charsetName.

String encodedUrl = URLEncoder.encode(url,"UTF-8");

How to use :

String url ="http://www.domain.com";
String param1 ="?param1=";
Strinf param1value ="name'last";
String param2 ="&param2=";
Strinf param2value ="2014-31-10 11:40:00";
String encodeUrl = url +param1+ URLEncoder.encode(param1value,"UTF-8")+param2+URLEncoder.encode(param2value,"UTF-8");
like image 179
Haresh Chhelana Avatar answered Sep 29 '22 09:09

Haresh Chhelana


you can use

 String oldurl="http://pairdroid.com/whatsapp.php?a=rajesh saini";
 String newurl=oldurl.replaceAll(" ","%20");
 URL url = new URL(newurl);
like image 25
raj Avatar answered Sep 29 '22 10:09

raj