`
默默的小熊
  • 浏览: 232960 次
社区版块
存档分类
最新评论

Request

 
阅读更多

import java.util.*;
import java.nio.*;
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import com.sun.net.httpserver.*;
import com.sun.net.httpserver.spi.*;

/**
 */
class Request {

    final static int BUF_LEN = 2048;
    final static byte CR = 13;
    final static byte LF = 10;

    private String startLine;
    private SocketChannel chan;
    private InputStream is;
    private OutputStream os;

    Request (InputStream rawInputStream, OutputStream rawout) throws IOException {
        this.chan = chan;
        is = rawInputStream;
        os = rawout;
        do {
            startLine = readLine();
            if (startLine == null) {
                return;
            }
            /* skip blank lines */
        } while (startLine == null ? false : startLine.equals (""));
    }


    char[] buf = new char [BUF_LEN];
    int pos;
    StringBuffer lineBuf;

    public InputStream inputStream () {
        return is;
    }

    public OutputStream outputStream () {
        return os;
    }

    /**
     * read a line from the stream returning as a String.
     * Not used for reading headers.
     */

    public String readLine () throws IOException {
        boolean gotCR = false, gotLF = false;
        pos = 0; lineBuf = new StringBuffer();
        while (!gotLF) {
            int c = is.read();
            if (c == -1) {
                return null;
            }
            if (gotCR) {
                if (c == LF) {
                    gotLF = true;
                } else {
                    gotCR = false;
                    consume (CR);
                    consume (c);
                }
            } else {
                if (c == CR) {
                    gotCR = true;
                } else {
                    consume (c);
                }
            }
        }
        lineBuf.append (buf, 0, pos);
        return new String (lineBuf);
    }

    private void consume (int c) {
        if (pos == BUF_LEN) {
            lineBuf.append (buf);
            pos = 0;
        }
        buf[pos++] = (char)c;
    }

    /**
     * returns the request line (first line of a request)
     */
    public String requestLine () {
        return startLine;
    }

    Headers hdrs = null;

    Headers headers () throws IOException {
        if (hdrs != null) {
            return hdrs;
        }
        hdrs = new Headers();

        char s[] = new char[10];
        int len = 0;

        int firstc = is.read();

        // check for empty headers
        if (firstc == CR || firstc == LF) {
            int c = is.read();
            if (c == CR || c == LF) {
                return hdrs;
            }
            s[0] = (char)firstc;
            len = 1;
            firstc = c;
        }

        while (firstc != LF && firstc != CR && firstc >= 0) {
            int keyend = -1;
            int c;
            boolean inKey = firstc > ' ';
            s[len++] = (char) firstc;
    parseloop:{
                while ((c = is.read()) >= 0) {
                    switch (c) {
                      case ':':
                        if (inKey && len > 0)
                            keyend = len;
                        inKey = false;
                        break;
                      case '\t':
                        c = ' ';
                      case ' ':
                        inKey = false;
                        break;
                      case CR:
                      case LF:
                        firstc = is.read();
                        if (c == CR && firstc == LF) {
                            firstc = is.read();
                            if (firstc == CR)
                                firstc = is.read();
                        }
                        if (firstc == LF || firstc == CR || firstc > ' ')
                            break parseloop;
                        /* continuation */
                        c = ' ';
                        break;
                    }
                    if (len >= s.length) {
                        char ns[] = new char[s.length * 2];
                        System.arraycopy(s, 0, ns, 0, len);
                        s = ns;
                    }
                    s[len++] = (char) c;
                }
                firstc = -1;
            }
            while (len > 0 && s[len - 1] <= ' ')
                len--;
            String k;
            if (keyend <= 0) {
                k = null;
                keyend = 0;
            } else {
                k = String.copyValueOf(s, 0, keyend);
                if (keyend < len && s[keyend] == ':')
                    keyend++;
                while (keyend < len && s[keyend] <= ' ')
                    keyend++;
            }
            String v;
            if (keyend >= len)
                v = new String();
            else
                v = String.copyValueOf(s, keyend, len - keyend);
            hdrs.add (k,v);
            len = 0;
        }
        return hdrs;
    }

    /**
     * Implements blocking reading semantics on top of a non-blocking channel
     */

    static class ReadStream extends InputStream {
        SocketChannel channel;
        ByteBuffer chanbuf;
        byte[] one;
        private boolean closed = false, eof = false;
        ByteBuffer markBuf; /* reads may be satisifed from this buffer */
        boolean marked;
        boolean reset;
        int readlimit;
        static long readTimeout;
        ServerImpl server;
        final static int BUFSIZE = 8 * 1024;

        public ReadStream (ServerImpl server, SocketChannel chan) throws IOException {
            this.channel = chan;
            this.server = server;
            chanbuf = ByteBuffer.allocate (BUFSIZE);
            chanbuf.clear();
            one = new byte[1];
            closed = marked = reset = false;
        }

        public synchronized int read (byte[] b) throws IOException {
            return read (b, 0, b.length);
        }

        public synchronized int read () throws IOException {
            int result = read (one, 0, 1);
            if (result == 1) {
                return one[0] & 0xFF;
            } else {
                return -1;
            }
        }

        public synchronized int read (byte[] b, int off, int srclen) throws IOException {

            int canreturn, willreturn;

            if (closed)
                throw new IOException ("Stream closed");

            if (eof) {
                return -1;
            }

            assert channel.isBlocking();

            if (off < 0 || srclen < 0|| srclen > (b.length-off)) {
                throw new IndexOutOfBoundsException ();
            }

            if (reset) { /* satisfy from markBuf */
                canreturn = markBuf.remaining ();
                willreturn = canreturn>srclen ? srclen : canreturn;
                markBuf.get(b, off, willreturn);
                if (canreturn == willreturn) {
                    reset = false;
                }
            } else { /* satisfy from channel */
                chanbuf.clear ();
                if (srclen <  BUFSIZE) {
                    chanbuf.limit (srclen);
                }
                do {
                    willreturn = channel.read (chanbuf);
                } while (willreturn == 0);
                if (willreturn == -1) {
                    eof = true;
                    return -1;
                }
                chanbuf.flip ();
                chanbuf.get(b, off, willreturn);

                if (marked) { /* copy into markBuf */
                    try {
                        markBuf.put (b, off, willreturn);
                    } catch (BufferOverflowException e) {
                        marked = false;
                    }
                }
            }
            return willreturn;
        }

        public boolean markSupported () {
            return true;
        }

        /* Does not query the OS socket */
        public synchronized int available () throws IOException {
            if (closed)
                throw new IOException ("Stream is closed");

            if (eof)
                return -1;

            if (reset)
                return markBuf.remaining();

            return chanbuf.remaining();
        }

        public void close () throws IOException {
            if (closed) {
                return;
            }
            channel.close ();
            closed = true;
        }

        public synchronized void mark (int readlimit) {
            if (closed)
                return;
            this.readlimit = readlimit;
            markBuf = ByteBuffer.allocate (readlimit);
            marked = true;
            reset = false;
        }

        public synchronized void reset () throws IOException {
            if (closed )
                return;
            if (!marked)
                throw new IOException ("Stream not marked");
            marked = false;
            reset = true;
            markBuf.flip ();
        }
    }

    static class WriteStream extends java.io.OutputStream {
        SocketChannel channel;
        ByteBuffer buf;
        SelectionKey key;
        boolean closed;
        byte[] one;
        ServerImpl server;

        public WriteStream (ServerImpl server, SocketChannel channel) throws IOException {
            this.channel = channel;
            this.server = server;
            assert channel.isBlocking();
            closed = false;
            one = new byte [1];
            buf = ByteBuffer.allocate (4096);
        }

        public synchronized void write (int b) throws IOException {
            one[0] = (byte)b;
            write (one, 0, 1);
        }

        public synchronized void write (byte[] b) throws IOException {
            write (b, 0, b.length);
        }

        public synchronized void write (byte[] b, int off, int len) throws IOException {
            int l = len;
            if (closed)
                throw new IOException ("stream is closed");

            int cap = buf.capacity();
            if (cap < len) {
                int diff = len - cap;
                buf = ByteBuffer.allocate (2*(cap+diff));
            }
            buf.clear();
            buf.put (b, off, len);
            buf.flip ();
            int n;
            while ((n = channel.write (buf)) < l) {
                l -= n;
                if (l == 0)
                    return;
            }
        }

        public void close () throws IOException {
            if (closed)
                return;
            //server.logStackTrace ("Request.OS.close: isOpen="+channel.isOpen());
            channel.close ();
            closed = true;
        }
    }
}
 
分享到:
评论

相关推荐

    C# request获取参数.docx

    Request 对象提供了多种方式来获取请求参数,本文将详细介绍 Request.Params、Request、Request.QueryString、Request.Form 和 Request.Cookies 等对象的用法和区别。 一、Request.Params Request.Params 是所有 ...

    对Django 中request.get和request.post的区别详解

    Django 中request.get和request.post的区别 POST和GET差异: POST和GET是HTTP协议定义的与服务器交互的方法。GET一般用于获取/查询资源信息,而POST一般用于更新资源信息。另外,还有PUT和DELETE方法。 POST和GET都...

    PHP生成唯一RequestID类

    在IT行业中,尤其是在分布式系统开发中,跟踪请求的唯一标识符(Request ID)是非常重要的。Request ID可以帮助我们追踪和诊断跨服务的请求流程,提高问题定位的效率。本篇文章将详细探讨如何使用PHP来生成这样的...

    Request、Request.Form和Request.QueryString的区别

    在探讨Request、Request.Form和Request.QueryString的区别之前,我们先来明确一下它们在Web开发中的基本概念和作用。在Web应用程序中,服务器与客户端之间通过HTTP协议进行数据交换,这一过程涉及到了请求(Request)...

    request.getcontextPath()_详解

    request.getcontextPath()详解 request.getcontextPath()是Java Web开发中常用的方法,用于获取当前Web应用程序的Context Path。Context Path是指Web应用程序的根目录,例如,一个名为“myapp”的Web应用程序,...

    最新的yapi 的cross-request 的离线插件

    《详解Yapi的Cross-request离线插件:打造顺畅的API接口测试体验》 在现代软件开发中,API接口测试是不可或缺的一环。为了确保系统的稳定性和数据交互的正确性,开发者需要对API进行详尽的测试。Yapi,一个优秀的...

    了解JSP中request属性的用法

    了解 JSP 中 request 属性的用法 JSP 中 request 属性是最基本也是最重要的对象之一,它提供了大量的方法来获取客户端的请求信息和设置服务器端的响应信息。了解 request 属性的用法是 JSP 开发中最基本的要求。 ...

    requestrequest.js

    request

    c#Request关于Url分析

    `Request.Url`与`Request.RawUrl` - **`Request.Url`**:该属性返回一个`Uri`对象,表示客户端请求的完整URL。 - **示例**:如果用户请求的是`http://localhost:29161/article/detail/6.html`,那么`Request.Url`...

    Request.ServerVariables参数集

    ### Request.ServerVariables参数集详解 在Web开发领域中,服务器端脚本经常需要获取与当前请求相关的各种环境变量,以实现更加智能、安全且高效的功能处理。`Request.ServerVariables`正是一个非常重要的对象,它...

    spring 支持@RequestBody注解依赖包

    在本篇文章中,我们将深入探讨`@RequestBody`的工作原理以及与之相关的依赖包,特别是Jackson库在其中的作用。 首先,`@RequestBody`是Spring MVC框架的一部分,它遵循Model-View-Controller(MVC)设计模式。在MVC...

    Request.QueryString 乱码问题

    ### Request.QueryString 乱码问题解析及解决方案 在Web开发中,经常会遇到通过URL传递参数的情况。其中,`Request.QueryString`是ASP.NET中用于获取URL查询字符串(即URL中问号后的部分)的一种常用方法。然而,在...

    PHP - HTTP_Request2实现短信验证码注册登录完整示例:PHP -HTTP_Request2.php和附件说明.rar

    $request-&gt;setBody(array( 'phone' =&gt; '+861234567890', 'code' =&gt; '1234' )); $response = $request-&gt;send(); ``` 3. **验证验证码**:用户输入验证码后,服务器端需要验证输入的验证码是否与之前生成并发送...

    IDEA Fast xxx Request

    C:\Users\XXX\AppData\Roaming\JetBrains\IntelliJIdea2023.1\plugins\Restful Fast Request\lib 注意! IDEA安装后需要激活码,关闭,会自动推出,不用管也不用重新打开,执行下面操作。 下载该资源后,先备份原版...

    【ASP.NET编程知识】ASP.NET Core读取Request.Body的正确方法.docx

    ASP.NET Core 读取 Request.Body 的正确方法 ASP.NET Core 读取 Request.Body 的正确方法是 ASP.NET Core 开发中一个常见的问题。许多开发者在读取 Request.Body 时都会遇到一些问题,本文将详细介绍读取 Request....

    java中对象的作用,如何获取Request对象

    Request对象在Web应用中的主要作用有以下几点: 1. **参数获取**:Request对象可以用来获取HTTP请求中携带的参数,包括URL参数和POST数据。通过`getParameter()`和`getParameterValues()`方法,开发者可以获取单个...

    java web 修改request携带的参数信息

    Request对象封装了客户端发送到服务器的所有数据,包括URL参数、请求头、请求体等。在某些场景下,可能需要对这些参数信息进行修改,比如安全过滤、数据校验或者日志记录等。本程序就是针对这种情况设计的一个实用...

    asp对象-Request

    ### ASP对象—Request详解 #### 一、概述 在ASP(Active Server Pages)环境中,`Request`对象主要用于从客户端获取信息。这些信息包括通过HTTP请求发送的数据,例如表单提交的信息、URL中的查询字符串等。此外,`...

    wx.request逆向笔记

    frida虽然确实调试起来相当方便,但是Xposed由于能够安装在用户手机上实现持久化的hook,至今受到很多人的青睐,对于微信小程序的wx.request API,本文将以该API作为用例,介绍如何使用Xposed来对微信小程序的js ...

    微信小程序踩坑系列——从wx.request谈谈异步处理

    见到wx.request的第一眼,就让我想起了$.ajax这东西,使用起来确实有很多不方便,不能忍,幸好小程序是支持ES6语法的,所以可以使用promise稍加改造。 先来说说wx.request为什么不能忍。 铺垫:“看得见却抓不住“的...

Global site tag (gtag.js) - Google Analytics