title: Connection to a URL from within an applet using Apache's HttpClient vs using the JDK's URLConnection
body: <p>In the following code, I have verified that connecting to a URL from within an applet preserves the browser's session if JDK's URLConnection class is used.  However, this is not the case if Apache's HttpClient library is used.  Does anyone know why?  Alternatively, is there a way for me to set the connection instance to be used by an HttpClient instance?</p>
  
  <pre><code>import java.applet.Applet;
  import java.io.IOException;
  import java.io.InputStream;
  import java.net.HttpURLConnection;
  import java.net.URISyntaxException;
  import java.net.URL;
  
  import javax.net.ssl.SSLException;
  
  import org.apache.http.client.ClientProtocolException;
  import org.apache.http.client.HttpClient;
  import org.apache.http.client.methods.HttpPost;
  import org.apache.http.impl.client.BasicResponseHandler;
  import org.apache.http.impl.client.DefaultHttpClient;
  
  public class HttpClientTesterApplet extends Applet {
      private static final long serialVersionUID = -1599714556710568947L;
  
      public void testHttpClient() throws ClientProtocolException, IOException,
              URISyntaxException {
          URL url = new URL(String.format("%s://localhost:%s/%s/testHttpClient",
                  getParameter("protocol"), getParameter("port"),
                  getParameter("context")));
  
          HttpClient client = new DefaultHttpClient();
  
          HttpPost post = new HttpPost(url.toURI());
  
          System.out.println("Executing request " + post.getURI());
  
          try {
              System.out
                      .println(client.execute(post, new BasicResponseHandler()));
          } catch (SSLException e) {
              System.out.println(e.getMessage());
          }
  
          System.out.println("Executed request " + post.getURI());
  
          System.out.println("Opening connection " + url);
  
          HttpURLConnection urlConnection = (HttpURLConnection) url
                  .openConnection();
  
          System.out.println("Opened connection " + url);
  
          urlConnection.setRequestMethod("POST");
  
          System.out.println("Connecting");
  
          urlConnection.connect();
  
          System.out.println("Connected");
  
          InputStream inputStream = urlConnection.getInputStream();
  
          try {
              while (inputStream.read() != -1) {
                  System.out.println("Reading");
              }
          } finally {
              inputStream.close();
          }
      }
  }
  </code></pre>