/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package peaconnector;

import java.io.*;
import java.net.*;

/**
 *
 * @author Csubák Péter
 */
public class HttpRequest {

    private String data;
    private HttpURLConnection conn;
    private String answer;
    private String Method;


    public HttpRequest(URL url, String data){
        this.data = data;
        try {
            conn = (HttpURLConnection) url.openConnection();
        } catch (Exception e) {
            throw new PeaException("Can't find the server.");
        }
    }

    public boolean sendRequest(){
        try {
            conn.setRequestMethod(Method);
            conn.setAllowUserInteraction(false); 
            conn.setDoInput(true);
            conn.setUseCaches(false);

            if (Method.equals("POST")) {
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type", "text/xml");
                conn.setRequestProperty("Content-length", Integer.toString(data.length()));
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                System.out.println("küld: "+data);
                wr.write(data);
                wr.flush();
                wr.close();
            }else{
                return false;
            }

        } catch (Exception e) {
            System.out.println(e.toString()); //<-- majd ki kell szedni
            return false;
        }
        return true;
    }

    public String getTextAnswer() {
        String out = "";
        try {
            InputStream rawInStream = conn.getInputStream();
            BufferedReader rdr = new BufferedReader(new InputStreamReader(rawInStream));
            String line;
            while ((line = rdr.readLine()) != null) {
                out = out + (line);
            }
            rdr.close();
        } catch (Exception e) {
            throw new PeaException("Can't recive the answer.");
        }

        answer = out;
        return out;

    }


    public String getMethod() {
        return this.Method;
    }

    public void setMethod(String m) {
        this.Method = m;
    }

    public String getAnswer() {
        return (answer == null) ? getTextAnswer() : answer;
    }
}