8

i'm using URLCodec from Apache Commons Codec to encode URL, but it encode space as + NOT as %20

why? and what is the solution?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Adham
  • 63,550
  • 98
  • 229
  • 344
  • related http://stackoverflow.com/questions/2678551/when-to-encode-space-to-plus-and-when-to-20 – Bozho Feb 21 '11 at 21:22

3 Answers3

5

See this related question

Of course, you can always do url.replace("+", "%20"); if you need it (after encoding)

Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • @Johan: I deleted my comment before seeing yours, because I felt like I was sniping at Bozho, and that wasn't my intent. w3schools isn't very reliable. For instance, to pick a random example, if you relied on their description of the JavaScript `String#replace` function (http://www.w3schools.com/jsref/jsref_replace.asp), you wouldn't know that you can supply a function for the second parameter, which is *really useful*. – T.J. Crowder Feb 21 '11 at 21:25
  • @T.J. Crowder anyway thanks for pointing the unreliability of w3schools. I removed the quote anyway, it is not that much relevant anyway. – Bozho Feb 21 '11 at 21:26
  • 3
    *"Of course, you can always do `url.replace(" ", "%20");"`...* That would be a bad idea (you don't want to do this before encoding, you'll end up with an encoded `%`; and the space isn't there *after* encoding). You'd want `.encode(str).replace("+", "%20");`. – T.J. Crowder Feb 21 '11 at 21:27
  • @T.J. Crowder yup, you are right, I meant after the encoding, but forgot that it's turned into a plus :) – Bozho Feb 21 '11 at 21:29
2

Because + is an equally valid way of encoding a space. What are you trying to "solve"?

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
  • dear, i need that .. where i have web service that understand %20 and not + .. check both of these plz http://www.aydeena.com/Services/Search.svc/JSON/SearchByText/deira+city+center http://www.aydeena.com/Services/Search.svc/JSON/SearchByText/deira%20city%20center – Adham Feb 21 '11 at 21:19
  • 2
    @adham: In that case, that web service is not adhering to the standard. It should be fixed. – Matti Virkkunen Feb 21 '11 at 21:20
  • @adham: if your webservice can't decode a + as a space, it is broken and not the encoding. If the root cause, the non-conformant webservice, I would bet that some manual string processing is going on, and god forbid a regex, instead of using a decoding function designed to conform to the specification. –  Feb 21 '11 at 21:24
  • 4
    You're not supposed to decode + as a space in an URL for other than the query string – nos Feb 21 '11 at 21:28
2

The URLCodec encodes stuff suitable a submitted form, which is not the same as percent encoding a URL. There's more explanation in this question

See this question for how you should encode your URL.

Community
  • 1
  • 1
nos
  • 223,662
  • 58
  • 417
  • 506