Code example for URLConnection

Methods: getInputStream, getOutputStream, setDoOutput, setRequestProperty, setUseCaches

0
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try { 
            URL servletURL = new URL("http://localhost:8080/servlets-examples/servlet/HelloWorldExample");
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 8888));
            URLConnection servletConnect = servletURL.openConnection(proxy);
            servletConnect.setDoOutput(true); // to allow us to write to the URL
            servletConnect.setUseCaches(false); // Write the message to the servlet and not from the browser's cache
            servletConnect.setRequestProperty("Content-Type", "application/x-java-serialized-object");
            Person person = null;
            List<String> emails = new ArrayList<String>();
            emails.add("test@user.com");
            person = new Person("test", "user", emails, 234, 123);
            SearchObject search = new SearchObject(jTextField1.getText());
            ObjectOutputStream outputToServlet;
            outputToServlet = new ObjectOutputStream(servletConnect.getOutputStream());
            outputToServlet.writeObject(search);
            outputToServlet.flush(); //Cleanup
            outputToServlet.close();
            ObjectInputStream is = new ObjectInputStream(servletConnect.getInputStream());
 
            SearchResult returnedValue = (SearchResult) is.readObject();
            is.close();
            adminLb.setEnabled(returnedValue.getIsAdmin());