view http/HttpRequest.k @ 14:bc647a5f0421 draft

modify HttpRequest.k
author Nobuyasu Oshiro <dimolto@cr.ie.u-ryukyu.ac.jp>
date Tue, 29 May 2012 00:22:51 +0900
parents 0335cdd081d0
children 44e3247ed7c1
line wrap: on
line source

include "URL.k"

using konoha.socket.*;
using konoha.io.*;

class HttpRequest {

	URL u;
	Map<String,String> property = {};
	static final String httpVersion = "HTTP/1.1";
	static final int PORT = 80;
	String url, host, method, uri;
	String body;
	Socket socket;
	OutputStream out;
	InputStream in;

	HttpRequest(URL u) {
		this.u = u;
		property = {}; // Map instance must is initialize here
		this.method = "POST"; // default method is POST
		this.url = u.getUrl();
		this.host = u.getHost();
		this.uri = u.getUri();
	}

	void openConnection(int port=80) {
		this.socket = new Socket(this.host, port);
		this.out = this.socket.getOutputStream();
		this.in = this.socket.getInputStream();
	}

	void setRequestProperty(String key, String value) {
		property.set(key, value);
	}

	void printRequestProperty() {
		for (String key : property.keys())
			OUT << key +": " + property[key] << EOL;
	}

	void setBody(String body) {
		this.body = body;
	}

	void appendBody(String str) {
		this.body = this.body + str;
	}

	void output(OutputRequest out) {
		out <<< this.method + " " + this.uri + " " + this.httpVersion <<< EOL;
		out <<<  "HOST: " + this.host <<< EOL;
		for (String key : property.keys()) {
			out <<< key +": " + property[key] <<< EOL;
		}
		if (body.getSize() != 0) {
			out <<<  "Content-length: " + this.body.getSize() <<< EOL;			
		}
		out <<< EOL;		
		out <<< body <<< EOL;
		out.flush();
	}

	void printRequest() {
		output(OUT);
	}

	void writeRequest() {
		output(this.out);
	}

	int getBodySize() {
		return this.body.getSize();
	}

	OutputStream getOutputStream() {
		return this.out;
	}

	InputStream getInputStream() {
		return this.in;
	}

	void close() {
		out.close();
		in.close();
	}

}