0

I've created a basic server using Java servlets. What I'd like to do is implement a more liberal URI syntax by allowing non-alphanumeric characters in the URI's as long as they are %-hex encoded i.e two words.txt could be encoded as two%words.txt.

I'm not sure how to go about this. I've tried using java's .replace in the form of uri.replace(' ', '%') but this gives me a message format exception.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Adam Short
  • 498
  • 7
  • 28

1 Answers1

5

Have a look at http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLEncoder.html

String encoded = URLEncoder.encode("This string has spaces", "UTF-8");
thobens
  • 1,729
  • 1
  • 15
  • 34
  • I'm still getting an MessageFormatException when trying to run PUT test text.txt HTTP/1.1 - is there something I'm missing? i tried to encode my URI after parsing it. – Adam Short Apr 03 '14 at 15:12
  • have you tried to begin the URI with a `/`? How do you send the request? – thobens Apr 03 '14 at 15:35
  • I just tried with a '/' but no luck. This is how I encode: RequestMessage reqMsg = RequestMessage.parse(is); // gets the uri from the parsed request message uri = reqMsg.getURI(); String encodedUri = URLEncoder.encode(uri, "UTF-8"); And how I request: PUT /test spaces.txt HTTP/1.1 – Adam Short Apr 03 '14 at 15:48
  • I guess you need to put the encoded URI in the request and decode it after the request is parsed... – thobens Apr 03 '14 at 16:00
  • So it was proven to me that the client is responsible to properly encode the request URI. That means that you need to, like I stated above, encode the URI from your client, before sending the request (=> HTTP spec), and after receiving the request, decode the URI again. – thobens Apr 03 '14 at 23:40