httprequestmessage.java

来自「很棒的web服务器源代码」· Java 代码 · 共 883 行 · 第 1/2 页

JAVA
883
字号
// HttpRequestMessage.java// $Id: HttpRequestMessage.java,v 1.31 2003/02/16 22:54:51 ylafon Exp $// (c) COPYRIGHT MIT and INRIA, 1996.// Please first read the full copyright statement in file COPYRIGHT.htmlpackage org.w3c.www.http;import java.io.IOException;import java.io.OutputStream;import java.net.URL;import org.w3c.www.mime.MimeParser;import org.w3c.www.mime.MimeParserException;public class HttpRequestMessage extends HttpEntityMessage {    // HTTP Request message well-known headers    public static int H_ACCEPT              = 31;    public static int H_ACCEPT_CHARSET      = 32;    public static int H_ACCEPT_ENCODING     = 33;    public static int H_ACCEPT_LANGUAGE     = 34;    public static int H_AUTHORIZATION       = 35;    public static int H_EXPECT              = 36;    public static int H_FROM                = 37;    public static int H_HOST                = 38;    public static int H_IF_MODIFIED_SINCE   = 39;    public static int H_IF_MATCH            = 40;    public static int H_IF_NONE_MATCH       = 41;    public static int H_IF_RANGE            = 42;    public static int H_IF_UNMODIFIED_SINCE = 43;    public static int H_MAX_FORWARDS        = 44;    public static int H_PROXY_AUTHORIZATION = 45;    public static int H_RANGE               = 46;    public static int H_REFERER             = 47;    public static int H_TE                  = 48;    public static int H_USER_AGENT          = 49;    static {      registerHeader("Accept"		     , "org.w3c.www.http.HttpAcceptList"		     , H_ACCEPT);      registerHeader("Accept-Charset"		     , "org.w3c.www.http.HttpAcceptCharsetList"		     , H_ACCEPT_CHARSET);      registerHeader("Accept-Encoding"		     , "org.w3c.www.http.HttpAcceptEncodingList"		     , H_ACCEPT_ENCODING);      registerHeader("Accept-Language"		     , "org.w3c.www.http.HttpAcceptLanguageList"		     , H_ACCEPT_LANGUAGE);      registerHeader("Authorization"		     , "org.w3c.www.http.HttpCredential"		     , H_AUTHORIZATION);      registerHeader("From"		     , "org.w3c.www.http.HttpString"		     , H_FROM);      registerHeader("Host"		     , "org.w3c.www.http.HttpString"		     , H_HOST);      registerHeader("If-Modified-Since"		     , "org.w3c.www.http.HttpDate"		     , H_IF_MODIFIED_SINCE);      registerHeader("If-Match"		     , "org.w3c.www.http.HttpEntityTagList"		     , H_IF_MATCH);      registerHeader("If-None-Match"		     , "org.w3c.www.http.HttpEntityTagList"		     , H_IF_NONE_MATCH);      registerHeader("If-Range"		     , "org.w3c.www.http.HttpEntityTag"		     , H_IF_RANGE);      registerHeader("If-Unmodified-Since"		     , "org.w3c.www.http.HttpDate"		     , H_IF_UNMODIFIED_SINCE);      registerHeader("Max-Forwards"		     , "org.w3c.www.http.HttpInteger"		     , H_MAX_FORWARDS);      registerHeader("Proxy-Authorization"		     , "org.w3c.www.http.HttpCredential"		     , H_PROXY_AUTHORIZATION);      registerHeader("Range"		     , "org.w3c.www.http.HttpRangeList"		     , H_RANGE);      registerHeader("Referer"		     , "org.w3c.www.http.HttpString"		     , H_REFERER);      registerHeader("User-Agent"		     , "org.w3c.www.http.HttpString"		     , H_USER_AGENT);      registerHeader("Expect"		     , "org.w3c.www.http.HttpString"		     , H_EXPECT);      registerHeader("TE"		     ,  "org.w3c.www.http.HttpAcceptEncodingList"		     , H_TE);    }    /**     * The method to execute on the target resource.     */    protected String method = "GET".intern();    /**     * The target resource, identified by its URL.     */    protected URL    url    = null;    /**     * The proxy to use for that request, if any.     */    protected URL proxy = null;    protected String sProxy = null;    /**     * This message is about to be emited, emit the request-line first !     * @param out The output stream to emit the request to.     * @exception IOException If some IO error occured while emiting the     * request.     */    protected void startEmit(OutputStream out, int what) 	 throws IOException    {	if ((what & EMIT_HEADERS) != EMIT_HEADERS)	    return ;	// I am not sure (at all) whether this belongs here or in some subclass	if ((major >= 1) && ! hasHeader(H_HOST)) {	    String h = 		((((url.getPort()==80) && 		   url.getProtocol().equalsIgnoreCase("http")) || 		  ((url.getPort()==443) && 		   url.getProtocol().equalsIgnoreCase("https"))||		  (url.getPort() == -1))		 ? url.getHost()		 : url.getHost() + ":" + url.getPort());	    setHeaderValue(H_HOST, HttpFactory.makeString(h));	}	// Emit the request line:	HttpBuffer buf = new HttpBuffer();	buf.append(method);	buf.append(' ');	if ( proxy != null ) {	    buf.append(url.toExternalForm());	} else {	    String sUrl = url.getFile();	    // as to jdk1.4 getFile can be "" in that case	    // we can use it when method = OPTIONS	    if (sUrl.length() == 0) {		if (method == HTTP.OPTIONS) {		    buf.append('*');		} else {		    buf.append('/');		}	    } else {		buf.append(sUrl);	    }	}	buf.append(' ');	buf.append(getVersion());	buf.append('\r');	buf.append('\n');	buf.emit(out);    }    public void dump(OutputStream out) {	// Dump the reply status line first, and then the headers	try {	    startEmit(out, EMIT_HEADERS);	} catch (Exception ex) {	}	super.dump(out);    }    /**     * @return A boolean <strong>true</strong> if the MIME parser should stop     * parsing, <strong>false</strong> otherwise.     * @exception IOException If some IO error occured while reading the     * stream.     * @exception HttpParserException if parsing failed.     */    public boolean notifyBeginParsing(MimeParser parser)	throws HttpParserException, IOException    {	// Append the whole reply line in some buffer:	HttpBuffer buf = new HttpBuffer();	int        ch  = parser.read();	// A present for Netscape !	while((ch == '\r') || (ch == '\n')) {	    ch = parser.read();	}    loop:	while (true) {	    switch(ch) {	      case -1:		  throw new HttpParserException("End Of File");	      case '\r':		  if ((ch = parser.read()) != '\n')		      parser.unread(ch);		  break loop;	      case '\n':		  break loop;	      default:		  buf.append(ch);	    }	    ch = parser.read();	}	// Parse the bufer into HTTP version and status code	byte       line[] = buf.getByteCopy();	ParseState ps     = new ParseState();	ps.ioff      = 0;	ps.bufend    = line.length;	ps.separator = (byte) ' ';	// Get the method name:	if ( HttpParser.nextItem(line, ps) < 0 ) {	    throw new RuntimeException("Bad request, no method !");	}	setMethod(ps.toString(line));	// Get the URL path, or full URL	if ( HttpParser.nextItem(line, ps) < 0 ) {	    throw new RuntimeException("Bad request, no URL !");	}	setTarget(ps.toString(line));	// Get the version numbers:	HttpParser.skipSpaces(line, ps);	if ( ps.ioff + 5 < ps.bufend ) {	    ps.ioff += 5;	    ps.separator = (byte) '.';	    this.major = (short) HttpParser.parseInt(line, ps);	    ps.prepare();	    this.minor = (short) HttpParser.parseInt(line, ps);	    return false;	} else {	    this.major = 0;	    this.minor = 9;	    return true;	}    }    /**     * All the headers have been parsed, take any appropriate actions.     * Here we will verify that the request is HTTP/1.1 compliant     * for the Host header.     * @param parser The Mime parser.     * @exception MimeParserException if the parsing failed     * @exception IOException if an IO error occurs.     */    public void notifyEndParsing(MimeParser parser)	 throws HttpParserException, IOException    {	if (major == 1 && minor == 1) {	    if (getHost() == null) {		throw new HttpParserException("missing Host header", this);	    }	}    }    // FIXME - I really mean FIXME    String target = null;    protected void setTarget(String target) {	this.target = target;    }     protected String getTarget() {	return target;    }    /**     * Get this request's method.     * @return The request method, as a String.     */    public String getMethod() {	return method;    }    /**     * Set this request's method.     * @param mth The request method.     */    public void setMethod(String method) {	this.method = method.intern();    }    /**     * Get this request's target URI.     * This will only return the absolute path of the requested resource, even     * if the actual request came with the full path as an URI.     * @return An URL instance, or <strong>null</strong> if undefined.     */    public URL getURL() {	return url;    }    /**     * Set this request URI.     * The provided URI should only include the absolute path of the target     * request, see the <code>setHost</code> method for how to set the actual     * host of the target resource.     * @param url The target URL of the request, as an URL instance.     */    public void setURL(URL url) {	this.url = url;    }    /**     * Get the <code>min-fresh</code> directive value of the cache control     * header.     * @return The min-fresh value, as a number of seconds, or <strong>-1     * </strong> if undefined.     */    public int getMinFresh() {	HttpCacheControl cc = getCacheControl();	return (cc == null) ? -1 : cc.getMinFresh();    }    /**     * Set the <code>min-fresh</code> directive value of the cache control     * header.     * @param minfresh The min-fresh value, in seconds, or <strong>-1</strong>     * to reset value.     */    public void setMinFresh(int minfresh) {	HttpCacheControl cc = getCacheControl();	if ( cc == null ) {	    if ( minfresh == -1 ) {		return;	    }	    setCacheControl(cc = new HttpCacheControl(true));	}	cc.setMinFresh(minfresh);    }    /**     * Get the <code>max-stale</code> directive value of the cache control     * header.     * @return The max-stale value, as a number of seconds, or <strong>-1     * </strong> if undefined.     */    public int getMaxStale() {	HttpCacheControl cc = getCacheControl();	return (cc == null) ? -1 : cc.getMaxStale();    }    /**     * Set the <code>max-stale</code> directive value.     * @param maxstale A number of seconds giving the allowed drift for     * a resource that is no more valid, or <strong>-1</strong> to reset     * the value.     */    public void setMaxStale(int maxstale) {	HttpCacheControl cc = getCacheControl();	if ( cc == null ) {	    if ( maxstale == -1 ) {		return;	    }	    setCacheControl(cc = new HttpCacheControl(true));	}	cc.setMaxStale(maxstale);    }    // FIXME more cache control accessors    /**     * Get this request accept list.     * @return A list of Accept clauses encoded as an array of HttpAccept     * instances, or <strong>null</strong> if undefined.     */    public HttpAccept[] getAccept() {	HeaderValue value = getHeaderValue(H_ACCEPT);	return (value != null) ? (HttpAccept[]) value.getValue() : null;    }    /**     * Set the list of accept clauses attached to this request.     * @param accepts The list of accept clauses encoded as an array     * of HttpAccept instances, or <strong>null</strong> to reset the value.     */    public void setAccept(HttpAccept accepts[]) {	setHeaderValue(H_ACCEPT		       , ((accepts == null)			  ? null			  : new HttpAcceptList(accepts)));    }    /**     * Get the list of accepted charsets for this request.     * @return The list of accepted languages encoded as an array of     * instances of HttpAcceptCharset, or <strong>null</strong> if undefined.     */    public HttpAcceptCharset[] getAcceptCharset() {	HeaderValue value = getHeaderValue(H_ACCEPT_CHARSET);	return (value != null) ? (HttpAcceptCharset[]) value.getValue():null;    }    /**     * Set the list of accepted charsets for this request.     * @param charsets The list of accepted charsets, encoded as an array     * of HttpAcceptCharset instances, or <strong>null</strong> to reset     * the value.     */    public void setAcceptCharset(HttpAcceptCharset charsets[]) {	setHeaderValue(H_ACCEPT_CHARSET		       , ((charsets == null)			  ? null			  : new HttpAcceptCharsetList(charsets)));    }    /**     * Get the list of accepted encodings.     * @return A list of token describing the accepted encodings, or <strong>     * null</strong> if undefined.     */    public HttpAcceptEncoding[] getAcceptEncoding() {	HeaderValue value = getHeaderValue(H_ACCEPT_ENCODING);	return (value != null) ? (HttpAcceptEncoding[]) value.getValue():null;    }    /**     * Set the list of accepted encodings.     * @param encodings The list of accepted encodings, as an array,     * of HttpAcceptEncoding or <strong>null</strong> to reset the value.     */    public void setAcceptEncoding(HttpAcceptEncoding encoding[]) {	setHeaderValue(H_ACCEPT_ENCODING		       , ((encoding == null)			  ? null			  : new HttpAcceptEncodingList(encoding)));    }    /**

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?