How to access a servlet in Tomcat Contanier using Java I have a servlet deployed in a Tomcat Servlet Container in this link, http://localhost:9764/example/servlets/servlet/HelloWorldExample. I want to send a HTTP request to that servlet using Java. Just I want to get the return as a String. Currently I am using this code to do it, Is it OK to use this code?

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Client {

    public static void main(String[] args) {
        try {
            String webPage = "http://10.100.3.83:9764/example/servlets/servlet/HelloWorldExample";
            URL url = new URL(webPage);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.addRequestProperty("Name","andunslg");
            urlConnection.addRequestProperty("PW","admin");

            InputStream is = urlConnection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);

            int numCharsRead;
            char[] charArray = new char[1024];
            StringBuffer sb = new StringBuffer();
            while ((numCharsRead = isr.read(charArray)) &gt; 0) {
                sb.append(charArray, 0, numCharsRead);
            }
            String result = sb.toString();

            System.out.println("*** BEGIN ***");
            System.out.println(result);
            System.out.println("*** END ***");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
when you are sending any data to the servlet make sure it you send it via POST/GET depending on how sensitive the information is. In your case the user and password is sent through the get which is unsafe since it can be viewed by anyone. 

you can add.urlConnection.setRequestMethod("POST"); Also to get the response you have to send the request first , which in your case is missing.

dataInput= new DataOutputStream(urlConnection.getOutputStream());
String content = "param1=" + URLEncoder.encode("first parameter") 
         + "&amp;param2=" 
         + URLEncoder.encode("the second one...");

dataInput.writeBytes(content);
dataInput.flush();
dataInput.close();