The following code exist on
http://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
Which is the oracle tutorial website.
My problem is with understanding the servlet. As you can see in documentation at the bottom of the page it says:
If your ReverseServlet is located at http://example.com/servlet/ReverseServlet, then when you run the Reverse program using
http://example.com/servlet/ReverseServlet “Reverse Me”
To run this example I tested my program with this link
http://docs.oracle.com/javase/tutorial/networking/urls/examples/ReverseServlet.java “Reverse Me”
and I got this error:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://docs.oracle.com/javase/tutorial/networking/urls/examples/ReverseServlet.java
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
at DemoURL.main(DemoURL.java:28)
Is it the place that my ReverseServlet is located or I’m totally wrong. If this not the correct way how can I run this program to check this example in tutorial?
Here is the code I have changed the class name:
import java.io.*;
import java.net.*;
public class DemoURL {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Usage: java Reverse "
+ "http://<location of your servlet/script>"
+ " string_to_reverse");
System.exit(1);
}
String stringToReverse = URLEncoder.encode(args[1], "UTF-8");
URL url = new URL(args[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("string=" + stringToReverse);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}
}
The url you use http://docs.oracle.com/javase/tutorial/networking/urls/examples/ReverseServlet.java does not contain a running version of the reverse servlet, just the source.
If you want to run the servlet you need to compile it and deploy the servlet yourself in a servlet container of your choice such as Tomcat, Jetty or similar. The servlet container handles accepting the request,parsing it and passing the request to the servlet.
Here is a description of how to (relatively) easily run a servlet Fastest way to deploy a Java servlet.