Hi all,
I am trying to create my first servlet with a basic client that sends some data to the servlet and gets a reply back.
I want to do that in order do go further where i want to develop an android app that communicates with a server. I actually did a small application that does prety much what i need, but i used sockets, and there is no way i can find to post that java socket server on the internet in order to connect with my android application. So from what i have read online, i figured that i need a servlet in order to have the ability to publish it online.
Most of the servlet examples i found were communicating with a web browser (something that i dont need) and i found this tutorial with a client sending a string to the server and gets a reply.
This is the servlet code from the tutorial:
and this is the clientimport java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloJavaWorld extends HttpServlet { private final static String _USERNAME = "username"; protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { PrintWriter out = response.getWriter(); String username = request.getParameter( _USERNAME ); response.setContentType("text/html"); out.println(""); out.println(""); out.println("HelloWorld"); out.println("Hello " + username + "!"); } }
import java.io.*; import java.net.*; public class ContactServlet { public static void main( String [] args ) { try { URL url = new URL(" http://127.0.0.1:8080/test/FileCounter"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); BufferedWriter out = new BufferedWriter( new OutputStreamWriter( conn.getOutputStream() ) ); out.write("username=javaworld\r\n"); out.flush(); out.close(); BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream() ) ); String response; while ( (response = in.readLine()) != null ) { System.out.println( response ); } in.close(); } catch ( MalformedURLException ex ) { // a real program would need to handle this exception } catch ( IOException ex ) { System.out.println("ex.getMessage()); // a real program would need to handle this exception } } }
The thing is that i can not sent data from the client. The server is working OK, from a browser i get thissince i dont sent anything to get a reply.HTML Code:HelloWorld Hello null!
From the java client i get this exception
If i delete all the commands that have to do with the transmision from the client, i.e.Server returned HTTP response code: 405 for URL: http://127.0.0.1:8080/test/FileCounter
I am geting the same result as the web browserBufferedWriter out = new BufferedWriter( new OutputStreamWriter( conn.getOutputStream() ) ); out.write("username=javaworld\r\n"); out.flush(); out.close();
HelloWorld Hello null!
Does anyone have ANY idea why this is happening? I dont know much about servlets (as you might guessed) and a ready tutorial shouldn't give me this much trouble.
thanks in advance,
ilias