How to represent a string URL for special character? - java

I am newbie to this and couldn't find exact answer. I have special characters in a URL such as,
"&", "#", "?" "<"
it causes a problems. (If someone can suggest how to deal with such situation then it would be an additional help). My main problem is that, how can I represent a string literal in JAVA for following kind of URL ?
"x###y"
I learned that we need to put its hex code value (using %). Can someone suggest that exact answer to fix this URL problem ?

You'll need to URL encode the address.
See :-
http://download.oracle.com/javase/1.5.0/docs/api/java/net/URLEncoder.html

java.net.URLEncoder.encode(YOUR_STRING, "UTF-8");
See also this question for a way to only encode the part of the url you need:

The answer depends on where the data is in the URL. There will be different encoding rules for different parts of the URL.
The exact form may also depend on what URI format the server is expecting.
Parameters in the query part can usually be encoded as application/x-www-form-urlencoded using the URLEncoder:
String query = URLEncoder.encode("key1", "UTF-8")
+ "="
+ URLEncoder.encode("value1", "UTF-8")
+ "&"
+ URLEncoder.encode("key2", "UTF-8")
+ "="
+ URLEncoder.encode("value2", "UTF-8");
If you need to encode in other parts of the URI (the path part, or the fragment part) read this.

URLEncoder is not for encoding URLs it is there to encode form data
see the following link for more details
HTTP URL Address Encoding in Java

Related

Need to replace spaces inside string with percentual symbol Java

I need to replace the spaces inside a string with the % symbol but I'm having some issues, what I tried is:
imageUrl = imageUrl.replace(' ', "%20");
But It gives me an error in the replace function.
Then:
imageUrl = imageUrl.replace(' ', "%%20");
But It still gives me an error in the replace function.
The I tried with the unicode symbol:
imageUrl = imageUrl.replace(' ', (char) U+0025 + "20");
But it still gives error.
Is there an easy way to do it?
String.replace(String, String) is the method you want.
replace
imageUrl.replace(' ', "%");
with
imageUrl.replace(" ", "%");
System.out.println("This is working".replace(" ", "%"));
I suggest you to use a URL Encoder for Encoding Strings in java.
String searchQuery = "list of banks in the world";
String url = "http://mypage.com/pages?q=" + URLEncoder.encode(searchQuery, "UTF-8");
I've ran into issues like this in the past with certain frameworks. I don't have enough of your code to know for sure, but what might be happening is whatever http framework you are using, in my case it was spring, is encoding the URL again. I spent a few days trying to solve a similar problem where I thought that string replace and the URI.builder() was broken. What ended up being the problem was that my http framework had taken my encoded url, and encoded it again. that means that any place it saw a "%20", it would see the '%' charictor and switch it out for '%' http code, "%25", resulting in. "%2520". The request would then fail because %2520 didn't translate into the space my server was expecting. While the issue apeared to be one of my encoding not working, it was really an issue of encoding too many times. I have an example from some working code in one of my projects below
//the Url of the server
String fullUrl = "http://myapiserver.com/path/";
//The parameter to append. contains a space that will need to be encoded
String param 1 = "parameter 1"
//Use Uri.Builder to append parameter
Uri.Builder uriBuilder = Uri.parse(fullUrl).buildUpon();
uriBuilder.appendQueryParameter("parameter1",param1);
/* Below is where it is important to understand how your
http framework handles unencoded url. In my case, which is Spring
framework, the urls are encoded when performing requests.
The result is that a url that is already encoded will be
encoded twice. For instance, if you're url is
"http://myapiserver.com/path?parameter1=param 1"
and it needs to be read by the server as
"http://myapiserver.com/path?parameter1=param%201"
it makes sense to encode the url using URI.builder().append, or any valid
solutions listed in other posts. However, If the framework is already
encoding your url, then it is likely to run into the issue where you
accidently encode the url twice: Once when you are preparing the URL to be
sent, and once again when you are sending the message through the framework.
this results in sending a url that looks like
"http://myapiserver.com/path?parameter1=param%25201"
where the '%' in "%20" was replaced with "%25", http's representation of '%'
when what you wanted was
"http://myapiserver.com/path?parameter1=param%201"
this can be a difficult bug to squash because you can copy the url in the
debugger prior to it being sent and paste it into a tool like fiddler and
have the fiddler request work but the program request fail.
since my http framework was already encoding the urls, I had to unencode the
urls after appending the parameters so they would only be encoded once.
I'm not saying it's the most gracefull solution, but the code works.
*/
String finalUrl = uriBuilder.build().toString().replace("%2F","/")
.replace("%3A", ":").replace("%20", " ");
//Call the server and ask for the menu. the Menu is saved to a string
//rest.GET() uses spring framework. The url is encoded again as
part of the framework.
menuStringFromIoms = rest.GET(finalUrl);
There is likely a more graceful way to keep a url from encoding twice. I hope this example helps point you on the right direction or eliminate a possability. Good luck.
Try this:
imageUrl = imageUrl.replaceAll(" ", "%20");
Replace spaces is not enought, try this
url = java.net.URLEncoder.encode(url, "UTF-8");

What type of Charset URL encoding should this use?

I have a rest api and when I enter a URL in the browser, part of the URL looks like this:
...where+%7B%0D%0A%3Fs+<http%3A%2F%2F...
which actually stands for
...where { ?s <http://...
Now, when I have to call the same URl through my JAVA code, I know of URLEncoder using which I am encoding the URL. When I use "UTF-8" format, the "<" in the URL is also encoded as %3C.
Is there any way of encoding such that the "<" and ">" are retained while other parts of the URL such as spaces and others are encoded properly.
The reason "<" get's encoded is because it's not a legal URI character. It has nothing to do with the character encoding.
If the server doesn't treat the escape sequence correctly then it needs to get fixed.
You can do
URLEncoder.encode(urlString).replace("%3C", "<")
URLEncoder.encode(url, "UTF-8").replaceAll("%3C", "<").replaceAll("%3E", ">");

ajax - Why jquery replaces "+" with a space (" ")?

I am having a problem here. When I use ajax to pass a parameter containing "+" to my controller it is being replaced by a space.
Example, I will pass value = Tom+Jerry+Garfield using ajax. When I use System.out.println() in my controller it displays Tom Jerry Garfield. I tried using other special characters I don't seem to have a problem.
Please help. Thanks in advance.
In some GET and POST requests (most likely in the URL, or via a form), spaces are encoded as "+" (plus) symbols before they are passed to the server. You can see this behaviour if you do a normal GET request - you will see something like google.com?q=test+example If you want to pass a plus symbol via an ajax GET/POST request, you need to "urlencode" it. The URL encoded value for + is %2B.
Also note:
The javascript encodeURIComponent() function can be used, as answered in:
AJAX POST and Plus Sign ( + ) -- How to Encode?
+ is decoded as space after url decoding. If you want to pass +, you need to encode it.
When we pass values to the controller there is a model binder which is sitting in between the request. When the ajax call is made the url and the request is encoded. The " " (Space) character in url decoded form encodes to a "+".
The Model Binder on the other hand decodes the request and extracts the parameters and gives it to the controller and hence "+" is converted to a " " .
But here the question is why would one pass "+" as a separator ??

Escape '+' sign in the request URL parameters

In our application some URLs are generated by appending the request params, some of these request params are used on those URLs for generating few labels, we are encoding these texts like below before generating the links:
title = URLEncoder.encode(match.getTitle(), "UTF-8");
When on the URL a '+' sign renders as blank, which is probably due to the fact that URL is considering the + as a space instead of a char, The URL is embedded in a static mail file which is not a part of application hence this dirty coding of appending the params to URL is done.
Please let me know if there is something that can be done to handle these kind of cases.
Thanks and Regards,
Vaibhav
+ should encode to %2B not space. But if it doesn't match.getTitle().replaceAll("+", "%2B");
and it should decode to + at the other end.

bad encoding for xml

I have a string like this " <person name="peter" ><\person>"
URL encoding
URLEncoder.encode(person.toString(),"UTF-8");
but the encoding is bad because for spaces make + insted of %20 and for = he gives other values can you guys help me?
This is exactly as specified in the URLEncoder javaDoc. Space is converted to + and = is "unsafe" and thus encoded to %3D.
If you need a %20 instead of the +, just do some post processing:
URLEncoder.encode(person.toString(),"UTF-8").replace("+", "%20");
Considering your comment I assume you want to decode the webservice answer.
// the answer you receive from the webservice
string webserviceResponse = "%3Cperson+name%3D%22peter%22%3E%3C%2Fperson%3E";
// turn into a "good" Xml string
string person = URLDecoder.decode(webserviceResponse, "UTF-8");
will give you
<person name="peter"></person>
as the value of person.

Categories