Mercurial > hg > Members > nobuyasu > konoha
view http/HttpRequest.k @ 12:da5149cbb9f4 draft
add http/test/urlTest.k
author | Nobuyasu Oshiro <dimolto@cr.ie.u-ryukyu.ac.jp> |
---|---|
date | Mon, 28 May 2012 22:39:46 +0900 |
parents | b1dc0a0565f2 |
children | 0335cdd081d0 |
line wrap: on
line source
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(); } int getBodySize() { return this.body.getSize(); } 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(); }