Mercurial > hg > Members > nobuyasu > konoha
changeset 9:b1dc0a0565f2
add http/HttpRequest
author | Nobuyasu Oshiro <dimolto@cr.ie.u-ryukyu.ac.jp> |
---|---|
date | Sun, 27 May 2012 21:05:29 +0900 |
parents | e5dadeae47cc |
children | 888143c20a4c |
files | http/HttpRequest.k |
diffstat | 1 files changed, 116 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/http/HttpRequest.k Sun May 27 21:05:29 2012 +0900 @@ -0,0 +1,116 @@ +using konoha.socket.*; +using konoha.io.*; + +class HttpRequest { + + String httpVersion; + Map<String,String> property = {}; + static final String httpVersion = "HTTP/1.1"; + static final String acceptString = "text/html"; + String host, method, uri; + String body; + Socket socket; + OutputStream out; + InputStream in; + + HttpRequest() { + property = {}; + this.method = "GET"; + this.httpVersion = "HTTP/1.1" + } + + void setUri(String uri) { + this.uri = uri; + } + void setMethod(String method) { + this.method = method; + } + + void openConnection(String host, int port=80) { + this.host = host; + this.socket = new Socket(host, port); + this.out = this.socket.getOutputStream(); + this.in = this.socket.getInputStream(); + } + + void setRequestProperty(String key, String value) { + property.set(key, value); + } + + void printRequestProperty() { + foreach (String key in property.keys()) + OUT << key +": " + property[key] << EOL; + } + + void setBody(String body) { + this.body = body; + } + + void appendBody(String str) { + this.body = this.body + str; + } + + void printRequest() { + OUT <<< this.method + " /" + this.uri + " " + this.httpVersion<<< EOL; + OUT <<< "HOST: " + this.host <<< EOL; + for (String key : property.keys()) { + OUT <<< key +": " + property[key] <<< EOL; + } + OUT <<< EOL; + OUT <<< body <<< EOL; + } + + void writeRequest() { + out <<< this.method + " /" + this.uri + " HTTP/1.1" <<< EOL; + out <<< "HOST: " + this.host <<< EOL; + for (String key : property.keys()) { + OUT <<< key +": " + property[key] <<< EOL; + } + out <<< EOL; + out <<< body <<< EOL; + out.flush(); + } + + OutputStream getOutputStream() { + return this.out; + } + + InputStream getInputStream() { + return this.in; + } + + void close() { + out.close(); + in.close(); + } + +} + +void printResponse(InputStream in) { + print("print Response"); + while ( !in.isClosed() ) { + String ret = in.readLine(); + OUT << ret << EOL; + } +} + + +void main(String[] args) +{ + HttpRequest r = new HttpRequest(); + r.openConnection("localhost"); + r.setMethod("POST"); + r.setUri("index.html"); + r.setRequestProperty("Connection","close"); + r.setRequestProperty("Accept-Charset","UTF-8"); + r.setRequestProperty("Cache-Control","no-cache"); + r.setRequestProperty("Accept-Language","en"); + r.writeRequest(); + + InputStream in = r.getInputStream(); + printResponse(in); + + r.close(); + + +} \ No newline at end of file