
package samplehttp.client;

//Import statements
import java.io.*;

import java.net.*;
import java.util.*;



/**
 * This is the class for non https communication
 */
public class Sender {


    String       hostname;
    String       servlet;
    int          port;
    String       timetowait;
    int      flgejb;

    final String HTTP           = "HTTP/1.1";
    final String METHOD         = "POST ";
    final String CONTENT_TYPE   = "Content-type: application/x-www-form-urlencoded";
    final String CONTENT_LENGTH = "Content-length: ";


    /**
     * Constructor Sender
     *
     *
     * @param hostname
     * @param servlet
     * @param port
     *
     */
    public Sender(String hostname, String servlet,
                               int port, String  timetowait, int flgejb) {

        this.hostname = hostname;
        this.servlet  = servlet;
        this.port     = port;
        this.timetowait     = timetowait;
        this.flgejb     = flgejb;
    }

    /**
     * execute: connect to a servlet and send something
     */
    public void execute() throws IOException{

        StringBuffer b = new StringBuffer("http://");

        b.append(hostname);
        b.append(':');
        b.append(port);
        b.append('/');
        b.append(servlet);

        URL       url  = new URL(b.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 
    
        conn.setRequestProperty("Connection","Close");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        PrintWriter stream = new PrintWriter(conn.getOutputStream(),
                                                 true);

        // Send 
        
        stream.println("param= " + timetowait+ " "+flgejb );
        System.out.println("timetowait "+timetowait);
  
        stream.close();

        BufferedReader reader =
            new BufferedReader(new InputStreamReader(conn
                .getInputStream()));

        // Check for response "200 OK"
        boolean ok = false;

        System.err.println("Reading response");
        StringBuffer response = new StringBuffer();
        String       r        = null;

        for (;;) {
            r = reader.readLine();

            if (r == null) {
                break;
            }

            response.append(r);
            if (r.indexOf("OK") != -1) {
                ok = true;

                break;
            }
        }

        System.err.println("Response received");
        reader.close();
        System.err.println("Connection closed");
        if (!ok) {
            System.out.println(">> Non OK");
        }

    }
}

