Some cleanup with HTTP classes

This commit is contained in:
Ziver Koc 2020-09-07 18:37:43 +02:00
parent 2249298c93
commit 337c0392bd
7 changed files with 709 additions and 633 deletions

View file

@ -31,13 +31,12 @@ import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
public class HttpHeader { public class HttpHeader {
// HTTP info
private boolean request = true; private boolean request = true;
private String type = "GET"; private String type = "GET";
private String url = "/"; private String url = "/";
private HashMap<String, String> urlAttributes; private HashMap<String, String> urlAttributes;
private float version = 1.0f; private float protocolVersion = 1.0f;
private int httpCode = 200; private int statusCode = 200;
private InputStream in; private InputStream in;
// Parameters // Parameters
@ -58,36 +57,42 @@ public class HttpHeader {
public boolean isResponse() { public boolean isResponse() {
return !request; return !request;
} }
/** /**
* @return true if this header represents a client request * @return true if this header represents a client request
*/ */
public boolean isRequest() { public boolean isRequest() {
return request; return request;
} }
/** /**
* @return the HTTP message type( ex. GET,POST...) * @return the HTTP message type( ex. GET,POST...)
*/ */
public String getRequestType() { public String getRequestType() {
return type; return type;
} }
/** /**
* @return the HTTP version of this header * @return the protocol version from this header
*/ */
public float getHTTPVersion(){ public float getProtocolVersion() {
return version; return protocolVersion;
} }
/** /**
* @return the HTTP Return Code from a Server * @return the HTTP Return Code from a Server
*/ */
public int getHTTPCode(){ public int getStatusCode() {
return httpCode; return statusCode;
} }
/** /**
* @return the URL that the client sent the server * @return the URL that the client sent the server
*/ */
public String getRequestURL() { public String getRequestURL() {
return url; return url;
} }
/** /**
* @return parses out the page name from the request url and returns it. * @return parses out the page name from the request url and returns it.
*/ */
@ -104,42 +109,49 @@ public class HttpHeader {
} }
return null; return null;
} }
/** /**
* @return a Iterator with all defined url keys * @return a Iterator with all defined url keys
*/ */
public Iterator<String> getURLAttributeKeys() { public Iterator<String> getURLAttributeKeys() {
return urlAttributes.keySet().iterator(); return urlAttributes.keySet().iterator();
} }
/** /**
* @return the URL attribute value of the given name. null if there is no such attribute * @return the URL attribute value of the given name. null if there is no such attribute
*/ */
public String getURLAttribute(String name) { public String getURLAttribute(String name) {
return urlAttributes.get(name); return urlAttributes.get(name);
} }
/** /**
* @return a Iterator with all defined headers * @return a Iterator with all defined headers
*/ */
public Iterator<String> getHeaderKeys() { public Iterator<String> getHeaderKeys() {
return headers.keySet().iterator(); return headers.keySet().iterator();
} }
/** /**
* @return the HTTP attribute value of the given name. null if there is no such attribute * @return the HTTP attribute value of the given name. null if there is no such attribute
*/ */
public String getHeader(String name) { public String getHeader(String name) {
return headers.get(name.toUpperCase()); return headers.get(name.toUpperCase());
} }
/** /**
* @return a Iterator with all defined cookies * @return a Iterator with all defined cookies
*/ */
public Iterator<String> getCookieKeys() { public Iterator<String> getCookieKeys() {
return cookies.keySet().iterator(); return cookies.keySet().iterator();
} }
/** /**
* @return the cookie value of the given name. null if there is no such attribute. * @return the cookie value of the given name. null if there is no such attribute.
*/ */
public String getCookie(String name) { public String getCookie(String name) {
return cookies.get(name); return cookies.get(name);
} }
/** /**
* @return a Reader that contains the body of the http request. * @return a Reader that contains the body of the http request.
*/ */
@ -148,22 +160,30 @@ public class HttpHeader {
} }
public void setIsRequest(boolean request) { this.request = request; } public void setIsRequest(boolean request) {
this.request = request;
}
public void setRequestType(String type) { public void setRequestType(String type) {
this.type = type; this.type = type;
} }
public void setHTTPVersion(float version){
this.version = version; public void setProtocolVersion(float version) {
this.protocolVersion = version;
} }
public void setHTTPCode(int code){
this.httpCode = code; public void setStatusCode(int code) {
this.statusCode = code;
} }
public void setRequestURL(String url) { public void setRequestURL(String url) {
this.url = url.trim().replaceAll("//", "/"); this.url = url.trim().replaceAll("//", "/");
} }
public void setHeader(String key, String value) { public void setHeader(String key, String value) {
this.headers.put(key.toUpperCase(), value); this.headers.put(key.toUpperCase(), value);
} }
protected void setInputStream(InputStream in) { protected void setInputStream(InputStream in) {
this.in = in; this.in = in;
} }
@ -171,19 +191,20 @@ public class HttpHeader {
protected HashMap<String, String> getHeaderMap() { protected HashMap<String, String> getHeaderMap() {
return headers; return headers;
} }
protected HashMap<String, String> getCookieMap() { protected HashMap<String, String> getCookieMap() {
return cookies; return cookies;
} }
protected HashMap<String, String> getUrlAttributeMap() { protected HashMap<String, String> getUrlAttributeMap() {
return urlAttributes; return urlAttributes;
} }
public String toString() { public String toString() {
StringBuilder tmp = new StringBuilder(); StringBuilder tmp = new StringBuilder();
tmp.append("{Type: ").append(type); tmp.append("{Type: ").append(type);
tmp.append(", HTTP_version: HTTP/").append(version); tmp.append(", HTTP_version: HTTP/").append(protocolVersion);
if (url == null) if (url == null)
tmp.append(", URL: null"); tmp.append(", URL: null");
else else

View file

@ -106,24 +106,23 @@ public class HttpHeaderParser {
// Server Response // Server Response
if (statusLine.startsWith("HTTP/")) { if (statusLine.startsWith("HTTP/")) {
header.setIsRequest(false); header.setIsRequest(false);
header.setHTTPVersion( Float.parseFloat( statusLine.substring( 5 , 8))); header.setProtocolVersion(Float.parseFloat(statusLine.substring(5, 8)));
header.setHTTPCode( Integer.parseInt( statusLine.substring( 9, statusLine.indexOf(' ', 9) ))); header.setStatusCode(Integer.parseInt(statusLine.substring(9, statusLine.indexOf(' ', 9))));
} }
// Client Request // Client Request
else if (statusLine.contains("HTTP/")) { else if (statusLine.contains("HTTP/")) {
header.setIsRequest(true); header.setIsRequest(true);
header.setRequestType(statusLine.substring(0, statusLine.indexOf(" ")).trim()); header.setRequestType(statusLine.substring(0, statusLine.indexOf(" ")).trim());
header.setHTTPVersion( Float.parseFloat( statusLine.substring(statusLine.lastIndexOf("HTTP/")+5 , statusLine.length()).trim())); header.setProtocolVersion(Float.parseFloat(statusLine.substring(statusLine.lastIndexOf("HTTP/") + 5).trim()));
statusLine = (statusLine.substring(header.getRequestType().length() + 1, statusLine.lastIndexOf("HTTP/"))); statusLine = (statusLine.substring(header.getRequestType().length() + 1, statusLine.lastIndexOf("HTTP/")));
// parse URL and attributes // parse URL and attributes
int index = statusLine.indexOf('?'); int index = statusLine.indexOf('?');
if (index > -1) { if (index > -1) {
header.setRequestURL(statusLine.substring(0, index)); header.setRequestURL(statusLine.substring(0, index));
statusLine = statusLine.substring( index+1, statusLine.length()); statusLine = statusLine.substring(index + 1);
parseURLParameters(header.getUrlAttributeMap(), statusLine); parseURLParameters(header.getUrlAttributeMap(), statusLine);
} } else {
else{
header.setRequestURL(statusLine); header.setRequestURL(statusLine);
} }
} }
@ -159,8 +158,9 @@ public class HttpHeaderParser {
* Parses a header value string that contains key and value paired data and * Parses a header value string that contains key and value paired data and
* stores them in a HashMap. If a pair only contain a key then the value * stores them in a HashMap. If a pair only contain a key then the value
* will be set as a empty string. * will be set as a empty string.
* * <p>
* TODO: method is not quote aware * TODO: method is not quote aware
*
* @param headerValue the raw header value String that will be parsed. * @param headerValue the raw header value String that will be parsed.
* @param delimiter the delimiter that separates key and value pairs (e.g. ';' for Cookies or ',' for Cache-Control) * @param delimiter the delimiter that separates key and value pairs (e.g. ';' for Cookies or ',' for Cache-Control)
*/ */
@ -169,12 +169,14 @@ public class HttpHeaderParser {
parseHeaderValues(map, headerValue, delimiter); parseHeaderValues(map, headerValue, delimiter);
return map; return map;
} }
/** /**
* Parses a header value string that contains key and value paired data and * Parses a header value string that contains key and value paired data and
* stores them in a HashMap. If a pair only contain a key then the value * stores them in a HashMap. If a pair only contain a key then the value
* will be set as a empty string. * will be set as a empty string.
* * <p>
* TODO: method is not quote aware * TODO: method is not quote aware
*
* @param map the Map where key and values will be stored. * @param map the Map where key and values will be stored.
* @param headerValue the raw header value String that will be parsed. * @param headerValue the raw header value String that will be parsed.
* @param delimiter the delimiter that separates key and value pairs (e.g. ';' for Cookies or ',' for Cache-Control) * @param delimiter the delimiter that separates key and value pairs (e.g. ';' for Cookies or ',' for Cache-Control)
@ -201,6 +203,7 @@ public class HttpHeaderParser {
public static void parseURLParameters(HttpHeader header, String urlAttributes) { public static void parseURLParameters(HttpHeader header, String urlAttributes) {
parseURLParameters(header.getUrlAttributeMap(), urlAttributes); parseURLParameters(header.getUrlAttributeMap(), urlAttributes);
} }
/** /**
* Parses a string with variables from a get or post request that was sent from a client * Parses a string with variables from a get or post request that was sent from a client
* *

View file

@ -36,8 +36,8 @@ import java.util.Map;
public interface HttpPage{ public interface HttpPage{
/** /**
* This method has to be implemented for every page. * This method has to be implemented for every page.
* This method is called when a client wants a response * The method is called when a client sends a request
* from this specific page. * and is expecting a response from the specific page.
* *
* @param out is a output stream to the client * @param out is a output stream to the client
* @param headers is the header received from the client * @param headers is the header received from the client

View file

@ -26,7 +26,6 @@ package zutil.net.http;
import zutil.converter.Converter; import zutil.converter.Converter;
import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.util.HashMap; import java.util.HashMap;
@ -36,35 +35,61 @@ import java.util.HashMap;
* It has buffer capabilities and cookie management. * It has buffer capabilities and cookie management.
* *
* @author Ziver * @author Ziver
*
*/ */
public class HttpPrintStream extends OutputStream { public class HttpPrintStream extends OutputStream {
// Defines the type of message /**
* Specifies if the HTTP message is a request (client) or a response (server).
*/
public enum HttpMessageType { public enum HttpMessageType {
REQUEST, REQUEST,
RESPONSE RESPONSE
} }
/** The actual output stream */ /**
* The actual output stream
*/
private PrintStream out; private PrintStream out;
/** This defines the supported http version */ /**
private String httpVersion; * This defines the type of message that will be generated
/** This defines the type of message that will be generated */ */
private HttpMessageType message_type; private final HttpMessageType messageType;
/** The status code of the message, ONLY for response */ /**
private Integer res_status_code; * Specifies the protocol that should be used
/** The request type of the message ONLY for request */ */
private String req_type; private String protocol;
/** The requesting url ONLY for request */ /**
private String req_url; * Specifies the protocol version that should be used
/** An Map of all the header values */ */
private String protocolVersion;
/**
* The status code of the message, ONLY for response
*/
private Integer responseStatusCode;
/**
* The request type of the message ONLY for request
*/
private String requestType;
/**
* The requesting url ONLY for request
*/
private String requestUrl;
/**
* An Map of all the header values
*/
private HashMap<String, String> headers; private HashMap<String, String> headers;
/** An Map of all the cookies */ /**
* An Map of all the cookies
*/
private HashMap<String, String> cookies; private HashMap<String, String> cookies;
/** The buffered header */ /**
* The header data buffer
*/
private StringBuffer buffer; private StringBuffer buffer;
/** If the header buffering is enabled */ /**
private boolean buffer_enabled; * If the header buffering is enabled
*/
private boolean bufferEnabled;
/** /**
* Creates an new instance of HttpPrintStream with * Creates an new instance of HttpPrintStream with
@ -75,6 +100,7 @@ public class HttpPrintStream extends OutputStream{
public HttpPrintStream(OutputStream out) { public HttpPrintStream(OutputStream out) {
this(out, HttpMessageType.RESPONSE); this(out, HttpMessageType.RESPONSE);
} }
/** /**
* Creates an new instance of HttpPrintStream with * Creates an new instance of HttpPrintStream with
* message type buffering disabled. * message type buffering disabled.
@ -84,15 +110,17 @@ public class HttpPrintStream extends OutputStream{
*/ */
public HttpPrintStream(OutputStream out, HttpMessageType type) { public HttpPrintStream(OutputStream out, HttpMessageType type) {
this.out = new PrintStream(out); this.out = new PrintStream(out);
this.httpVersion = "1.0"; this.protocol = "HTTP";
this.message_type = type; this.protocolVersion = "1.0";
this.res_status_code = 200; this.messageType = type;
this.responseStatusCode = 200;
this.headers = new HashMap<>(); this.headers = new HashMap<>();
this.cookies = new HashMap<>(); this.cookies = new HashMap<>();
this.buffer = new StringBuffer(); this.buffer = new StringBuffer();
this.buffer_enabled = false; this.bufferEnabled = false;
} }
/** /**
* Enable the buffering capability of the PrintStream. * Enable the buffering capability of the PrintStream.
* Nothing will be sent to the client when buffering * Nothing will be sent to the client when buffering
@ -100,16 +128,16 @@ public class HttpPrintStream extends OutputStream{
* This function will flush the stream if buffering is * This function will flush the stream if buffering is
* disabled. * disabled.
*/ */
public void enableBuffering(boolean enable) throws IOException { public void enableBuffering(boolean enable) {
buffer_enabled = enable; bufferEnabled = enable;
if(!buffer_enabled) flush(); if (!bufferEnabled) flush();
} }
/** /**
* Set the http version that will be used in the http header * Set the http version that will be used in the http header
*/ */
public void setHttpVersion(String version){ public void setProtocolVersion(String version) {
this.httpVersion = version; this.protocolVersion = version;
} }
/** /**
@ -117,11 +145,11 @@ public class HttpPrintStream extends OutputStream{
* *
* @param key is the name of the cookie * @param key is the name of the cookie
* @param value is the value of the cookie * @param value is the value of the cookie
* @throws IOException if the header has already been sent * @throws IllegalStateException if the header has already been sent
*/ */
public void setCookie(String key, String value) throws IOException{ public void setCookie(String key, String value) {
if (cookies == null) if (cookies == null)
throw new IOException("Header already sent!"); throw new IllegalStateException("Header already sent");
cookies.put(key, value); cookies.put(key, value);
} }
@ -130,11 +158,11 @@ public class HttpPrintStream extends OutputStream{
* *
* @param key is the header name * @param key is the header name
* @param value is the value of the header * @param value is the value of the header
* @throws IOException if the header has already been sent * @throws IllegalStateException if the header has already been sent
*/ */
public void setHeader(String key, String value) throws IOException{ public void setHeader(String key, String value) {
if (headers == null) if (headers == null)
throw new IOException("Header already sent!"); throw new IllegalStateException("Header already sent");
headers.put(key, value); headers.put(key, value);
} }
@ -142,46 +170,48 @@ public class HttpPrintStream extends OutputStream{
* Sets the status code of the message, ONLY available in HTTP RESPONSE * Sets the status code of the message, ONLY available in HTTP RESPONSE
* *
* @param code the code from 100 up to 599 * @param code the code from 100 up to 599
* @throws IOException if the header has already been sent or the message type is wrong * @throws IllegalStateException if the header has already been sent or the message type is wrong
*/ */
public void setStatusCode(int code) throws IOException{ public void setStatusCode(int code) {
if( res_status_code == null ) if (responseStatusCode == null)
throw new IOException("Header already sent!"); throw new IllegalStateException("Header already sent.");
if( message_type != HttpMessageType.RESPONSE ) if (messageType != HttpMessageType.RESPONSE)
throw new IOException("Status Code is only available in HTTP RESPONSE!"); throw new IllegalStateException("Status Code is only available with HTTP requests");
res_status_code = code; responseStatusCode = code;
} }
/** /**
* Sets the request type of the message, ONLY available in HTTP REQUEST * Sets the request type of the message, ONLY available in HTTP REQUEST
* *
* @param req_type is the type of the message, e.g. GET, POST... * @param req_type is the type of the message, e.g. GET, POST...
* @throws IOException if the header has already been sent or the message type is wrong * @throws IllegalStateException if the header has already been sent or the message type is wrong
*/ */
public void setRequestType(String req_type) throws IOException{ public void setRequestType(String req_type) {
if (req_type == null) if (req_type == null)
throw new IOException("Header already sent!"); throw new IllegalStateException("Header already sent.");
if( message_type != HttpMessageType.REQUEST ) if (messageType != HttpMessageType.REQUEST)
throw new IOException("Request Message Type is only available in HTTP REQUEST!"); throw new IllegalStateException("Request Message Type is only available with HTTP requests");
this.req_type = req_type; this.requestType = req_type;
} }
/** /**
* Sets the requesting URL of the message, ONLY available in HTTP REQUEST * Sets the requesting URL of the message. Only available with HTTP requests
* *
* @param req_url is the URL * @param req_url is the URL
* @throws IOException if the header has already been sent or the message type is wrong * @throws IllegalStateException if the header has already been sent or the message type is wrong
*/ */
public void setRequestURL(String req_url) throws IOException{ public void setRequestURL(String req_url) {
if (req_url == null) if (req_url == null)
throw new IOException("Header already sent!"); throw new IllegalStateException("Header already sent.");
if( message_type != HttpMessageType.REQUEST ) if (messageType != HttpMessageType.REQUEST)
throw new IOException("Request URL is only available in HTTP REQUEST!"); throw new IllegalStateException("Request URL is only available with a HTTP request");
this.req_url = req_url; this.requestUrl = req_url;
} }
protected void setHeaders(HashMap<String, String> map) { protected void setHeaders(HashMap<String, String> map) {
headers = map; headers = map;
} }
protected void setCookies(HashMap<String, String> map) { protected void setCookies(HashMap<String, String> map) {
cookies = map; cookies = map;
} }
@ -190,56 +220,58 @@ public class HttpPrintStream extends OutputStream{
/** /**
* Prints a new line * Prints a new line
*/ */
public void println() throws IOException { public void println() {
printOrBuffer(System.lineSeparator()); printOrBuffer(System.lineSeparator());
} }
/** /**
* Prints with a new line * Prints with a new line
*/ */
public void println(String s) throws IOException { public void println(String s) {
printOrBuffer(s + System.lineSeparator()); printOrBuffer(s + System.lineSeparator());
} }
/** /**
* Prints an string * Prints an string
*/ */
public void print(String s) throws IOException { public void print(String s) {
printOrBuffer(s); printOrBuffer(s);
} }
/** /**
* Will buffer String or directly output headers if needed and then the String * Will buffer the body data or directly send the headers if needed and then the append the body
*/ */
private void printOrBuffer(String s) { private void printOrBuffer(String s) {
if(buffer_enabled){ if (bufferEnabled) {
buffer.append(s); buffer.append(s);
} } else {
else{ if (responseStatusCode != null) {
if(res_status_code != null){ if (messageType == HttpMessageType.REQUEST)
if( message_type==HttpMessageType.REQUEST ) out.print(requestType + " " + requestUrl + " " + protocol + "/" + protocolVersion);
out.print(req_type + " " + req_url + " HTTP/"+httpVersion);
else else
out.print("HTTP/"+httpVersion+" " + res_status_code + " " + getStatusString(res_status_code)); out.print("HTTP/" + protocolVersion + " " + responseStatusCode + " " + getStatusString(responseStatusCode));
out.println(); out.println();
res_status_code = null; responseStatusCode = null;
req_type = null; requestType = null;
req_url = null; requestUrl = null;
} }
if (headers != null) { if (headers != null) {
for (String key : headers.keySet()) { for (String key : headers.keySet()) {
out.println(key + ": " + headers.get(key)); out.println(key + ": " + headers.get(key));
} }
headers = null; headers = null;
} }
if (cookies != null) { if (cookies != null) {
if (!cookies.isEmpty()) { if (!cookies.isEmpty()) {
if( message_type==HttpMessageType.REQUEST ){ if (messageType == HttpMessageType.REQUEST) {
out.print("Cookie: "); out.print("Cookie: ");
for (String key : cookies.keySet()) { for (String key : cookies.keySet()) {
out.print(key + "=" + cookies.get(key) + "; "); out.print(key + "=" + cookies.get(key) + "; ");
} }
out.println(); out.println();
} } else {
else{
for (String key : cookies.keySet()) { for (String key : cookies.keySet()) {
out.print("Set-Cookie: " + key + "=" + cookies.get(key) + ";"); out.print("Set-Cookie: " + key + "=" + cookies.get(key) + ";");
out.println(); out.println();
@ -254,36 +286,35 @@ public class HttpPrintStream extends OutputStream{
} }
/** /**
* @return if headers has been sent. The setHeader, setStatusCode, setCookie method will throw Exceptions * @return if headers has been sent. The setHeader, setStatusCode, setCookie method will throw IllegalStateException
*/ */
public boolean isHeaderSent() { public boolean isHeaderSent() {
return res_status_code == null && headers == null && cookies == null; return responseStatusCode == null && headers == null && cookies == null;
} }
/** /**
* Sends out the buffer and clears it * Sends out the buffer and clear it
*/ */
@Override @Override
public void flush() throws IOException { public void flush() {
flushBuffer(); flushBuffer();
out.flush(); out.flush();
} }
@Override @Override
public void close() throws IOException { public void close() {
flush(); flush();
out.close(); out.close();
} }
protected void flushBuffer() throws IOException { protected void flushBuffer() {
if(buffer_enabled){ if (bufferEnabled) {
buffer_enabled = false; bufferEnabled = false;
printOrBuffer(buffer.toString()); printOrBuffer(buffer.toString());
buffer.delete(0, buffer.length()); buffer.delete(0, buffer.length());
buffer_enabled = true; bufferEnabled = true;
} } else if (responseStatusCode != null || headers != null || cookies != null) {
else if(res_status_code != null || headers != null || cookies != null){
printOrBuffer(""); printOrBuffer("");
} }
} }
@ -292,49 +323,62 @@ public class HttpPrintStream extends OutputStream{
* Will flush all buffers and write binary data to stream * Will flush all buffers and write binary data to stream
*/ */
@Override @Override
public void write(int b) throws IOException { public void write(int b) {
flushBuffer(); flushBuffer();
out.write(b); out.write(b);
} }
/** /**
* * Will flush all buffers and write binary data to stream * * Will flush all buffers and write binary data to stream
*/ */
@Override @Override
public void write(byte[] buf, int off, int len) throws IOException { public void write(byte[] buf, int off, int len) {
flushBuffer(); flushBuffer();
out.write(buf, off, len); out.write(buf, off, len);
} }
private String getStatusString(int type) { private String getStatusString(int type) {
switch (type) { switch (type) {
case 100: return "Continue"; case 100:
case 200: return "OK"; return "Continue";
case 301: return "Moved Permanently"; case 200:
case 304: return "Not Modified"; return "OK";
case 307: return "Temporary Redirect"; case 301:
case 400: return "Bad Request"; return "Moved Permanently";
case 401: return "Unauthorized"; case 304:
case 403: return "Forbidden"; return "Not Modified";
case 404: return "Not Found"; case 307:
case 500: return "Internal Server Error"; return "Temporary Redirect";
case 501: return "Not Implemented"; case 400:
default: return ""; return "Bad Request";
case 401:
return "Unauthorized";
case 403:
return "Forbidden";
case 404:
return "Not Found";
case 500:
return "Internal Server Error";
case 501:
return "Not Implemented";
default:
return "";
} }
} }
public String toString() { public String toString() {
StringBuilder str = new StringBuilder(); StringBuilder str = new StringBuilder();
str.append("{http_type: ").append(message_type); str.append("{http_type: ").append(messageType);
if (res_status_code != null) { if (responseStatusCode != null) {
if (message_type == HttpMessageType.REQUEST) { if (messageType == HttpMessageType.REQUEST) {
str.append(", req_type: ").append(req_type); str.append(", req_type: ").append(requestType);
if(req_url == null) if (requestUrl == null)
str.append(", req_url: null"); str.append(", req_url: null");
else else
str.append(", req_url: \"").append(req_url).append('\"'); str.append(", req_url: \"").append(requestUrl).append('\"');
} else if (message_type == HttpMessageType.RESPONSE){ } else if (messageType == HttpMessageType.RESPONSE) {
str.append(", status_code: ").append(res_status_code); str.append(", status_code: ").append(responseStatusCode);
str.append(", status_str: ").append(getStatusString(res_status_code)); str.append(", status_str: ").append(getStatusString(responseStatusCode));
} }
if (headers != null) { if (headers != null) {
@ -343,8 +387,7 @@ public class HttpPrintStream extends OutputStream{
if (cookies != null) { if (cookies != null) {
str.append(", Cookies: ").append(Converter.toString(cookies)); str.append(", Cookies: ").append(Converter.toString(cookies));
} }
} } else
else
str.append(", HEADER ALREADY SENT "); str.append(", HEADER ALREADY SENT ");
str.append('}'); str.append('}');

View file

@ -210,7 +210,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{
} }
//**************************** RESPONSE ************************************ //**************************** RESPONSE ************************************
out.setHttpVersion("1.0"); out.setProtocolVersion("1.0");
out.setStatusCode(200); out.setStatusCode(200);
out.setHeader("Server", SERVER_NAME); out.setHeader("Server", SERVER_NAME);
out.setHeader("Content-Type", "text/html"); out.setHeader("Content-Type", "text/html");

View file

@ -61,15 +61,19 @@ public class HttpURL {
public String getProtocol() { public String getProtocol() {
return protocol; return protocol;
} }
public String getHost() { public String getHost() {
return host; return host;
} }
public int getPort() { public int getPort() {
return port; return port;
} }
public String getPath() { public String getPath() {
return path; return path;
} }
public String getAnchor() { public String getAnchor() {
return anchor; return anchor;
} }
@ -77,20 +81,25 @@ public class HttpURL {
public void setProtocol(String prot) { public void setProtocol(String prot) {
this.protocol = prot; this.protocol = prot;
} }
public void setHost(String host) { public void setHost(String host) {
this.host = host; this.host = host;
} }
public void setPort(int port) { public void setPort(int port) {
this.port = port; this.port = port;
} }
public void setPath(String path) { public void setPath(String path) {
if (path.length() >= 1 && !path.startsWith(PATH_SEPARATOR)) if (path.length() >= 1 && !path.startsWith(PATH_SEPARATOR))
path = PATH_SEPARATOR + path; path = PATH_SEPARATOR + path;
this.path = path; this.path = path;
} }
public void setAnchor(String anch) { public void setAnchor(String anch) {
this.anchor = anch; this.anchor = anch;
} }
public void setParameter(String key, String value) { public void setParameter(String key, String value) {
this.parameters.put(key, value); this.parameters.put(key, value);
} }
@ -101,7 +110,7 @@ public class HttpURL {
/** /**
* Generates the parameter string in a URL. * Generates the parameter string in a URL.
* * <p>
* e.g. * e.g.
* "key=value&amp;key2=value&amp;..." * "key=value&amp;key2=value&amp;..."
*/ */

View file

@ -36,7 +36,7 @@ public class HttpDigestAuthPageTest {
public void cleanRequest() throws IOException { public void cleanRequest() throws IOException {
HttpHeader rspHeader = HttpTestUtil.makeRequest(page); HttpHeader rspHeader = HttpTestUtil.makeRequest(page);
assertEquals(401, rspHeader.getHTTPCode()); assertEquals(401, rspHeader.getStatusCode());
assertNotNull(rspHeader.getHeader("WWW-Authenticate")); assertNotNull(rspHeader.getHeader("WWW-Authenticate"));
assertEquals("Digest", parseAuthType(rspHeader)); assertEquals("Digest", parseAuthType(rspHeader));
Map<String,String> authHeader = parseAuthHeader(rspHeader); Map<String,String> authHeader = parseAuthHeader(rspHeader);
@ -49,21 +49,21 @@ public class HttpDigestAuthPageTest {
@Test @Test
public void authenticate() throws IOException { public void authenticate() throws IOException {
HttpHeader rspHeader = authenticate(PAGE_USERNAME, PAGE_PASSWORD); HttpHeader rspHeader = authenticate(PAGE_USERNAME, PAGE_PASSWORD);
assertEquals(200, rspHeader.getHTTPCode()); assertEquals(200, rspHeader.getStatusCode());
assertThat(IOUtil.readContentAsString(rspHeader.getInputStream()), assertThat(IOUtil.readContentAsString(rspHeader.getInputStream()),
containsString(PAGE_CONTENT)); containsString(PAGE_CONTENT));
} }
@Test @Test
public void wrongUsername() throws IOException { public void wrongUsername() throws IOException {
HttpHeader rspHeader = authenticate(PAGE_USERNAME+"wrong", PAGE_PASSWORD); HttpHeader rspHeader = authenticate(PAGE_USERNAME+"wrong", PAGE_PASSWORD);
assertEquals(403, rspHeader.getHTTPCode()); assertEquals(403, rspHeader.getStatusCode());
assertThat(IOUtil.readContentAsString(rspHeader.getInputStream()), assertThat(IOUtil.readContentAsString(rspHeader.getInputStream()),
not(containsString(PAGE_CONTENT))); not(containsString(PAGE_CONTENT)));
} }
@Test @Test
public void wrongPassword() throws IOException { public void wrongPassword() throws IOException {
HttpHeader rspHeader = authenticate(PAGE_USERNAME, PAGE_PASSWORD+"wrong"); HttpHeader rspHeader = authenticate(PAGE_USERNAME, PAGE_PASSWORD+"wrong");
assertEquals(403, rspHeader.getHTTPCode()); assertEquals(403, rspHeader.getStatusCode());
assertThat(IOUtil.readContentAsString(rspHeader.getInputStream()), assertThat(IOUtil.readContentAsString(rspHeader.getInputStream()),
not(containsString(PAGE_CONTENT))); not(containsString(PAGE_CONTENT)));
} }