Do you know four scenarios for Http requests and responses in web projects

Keywords: Web Development Java Apache Web Server encoding

[Four cases]:

HttpRequest,HttpResponse,HttpServletRequest,HttpServletResponse
[What is HTTP?]
HyperText Transfer Protocol (HTTP) is a protocol designed to allow clients and servers to communicate smoothly.
HTTP works as a request-response protocol between the client and the server.
[Two commonly used methods of Http]
get - get data from the specified server
post - Submit data to the specified server for processing
[GET Method]
When using the GET method, the query string (key-value pair) is appended to the URL address and sent to the server together:
/test/demo_form.jsp?name1=value1&name2=value2
Characteristic:
A. Requests can be cached
B. Requests will be saved in the browser's history
C, Url can be saved as browser bookmarks
D, Request has a length limit [parameters with dozens of Id s, fewer parameters will be found]
E, get is a query, mainly used to get data
[POST Method:]
When using the POST method, the query string exists separately in the POST information and is sent to the server along with the HTTP request:
POST /test/demo_form.jsp HTTP/1.1
Host: w3schools.com
name1=value1&name2=value2
Characteristic:
A. Request cannot save cache
B. Requests cannot be saved as browser history
C. Request cannot save bookmark
D, unlimited length [so everything with most data is submitted as a post form]

mode describe
HEAD Similar to GET requests, unlike servers that return only HTTP header information, no page content
PUT Upload a description of the specified URL
DELETE Delete the specified resource
OPTIONS Return HTTP methods supported by the server
CONNECT Connection requests converted to transparent TCP/IP tunnels

1,HttpRequest

1.org.apache.http.HttpRequest handles Header-related titles [Java is not commonly used]

Method inherited from interface org.apache.http, HttpMessage, including:
[1]void addHeader(Header header)
Add a title to this message.
[2]void addHeader(String name, String value)
Add a title to this message.
[3]boolean containsHeader(String name)
Check for some headers in this message.
[4]Header[] getAllHeaders()
Returns all headers of this message.
[5]Header getFirstHeader(String name)
Returns the first header with the specified name of this message.
[6]Header[] getHeaders(String name)
Returns all headers with the specified name of this message.
[7]Header getLastHeader(String name)
Returns the last header with the specified name of this message.
[8]HttpParams getParams()
Not recommended.Use the provided configuration classes "org.apache.http.config" and "org.apache.http.client.config"
[9]ProtocolVersion getProtocolVersion()
Returns the message compatible protocol version.
[10]HeaderIterator headerIterator()
Returns iterators for all headers.
[11]HeaderIterator headerIterator(String name)
Returns an iterator with a header of a given name.
[12]void removeHeader(Header header)
Remove the title from this message.
[13]void removeHeaders(String name)
Remove all headers with a specific name from this message.
[14]void setHeader(Header header)
Overwrite the first header with the same name.
[15]void setHeader(String name, String value)
Overwrite the first header with the same name.
[16]void setHeaders(Header[] headers)
Overwrite all headings in the message.
[17]void setParams(HttpParams params)
Not recommended.Use the provided configuration classes "org.apache.http.config" and "org.apache.http.client.config"

    public interface HttpRequest extends HttpMessage {
                RequestLine getRequestLine();
        }

    public interface HttpMessage {
            ProtocolVersion getProtocolVersion();
            boolean containsHeader(String var1);
            Header[] getHeaders(String var1);
            Header getFirstHeader(String var1);
            Header getLastHeader(String var1);
            Header[] getAllHeaders();
            void addHeader(Header var1);
            void addHeader(String var1, String var2);
            void setHeader(Header var1);
            void setHeader(String var1, String var2);
            void setHeaders(Header[] var1);
            void removeHeader(Header var1);
            void removeHeaders(String var1);
            HeaderIterator headerIterator();
            HeaderIterator headerIterator(String var1);
            /** @deprecated */
            @Deprecated
            HttpParams getParams();
            /** @deprecated */
            @Deprecated
            void setParams(HttpParams var1);
    }

(2) Get URI from org.springframework.http.HttpRequest [Java is not commonly used]

public interface HttpRequest extends HttpMessage {
        @Nullable
        default HttpMethod getMethod() {
                return HttpMethod.resolve(this.getMethodValue());
        }
        String getMethodValue();
        URI getURI();
}

public interface HttpMessage {
        HttpHeaders getHeaders();
}

(3) org.jboss.netty.handler.codec.http.HttpRequest[Java is not commonly used]

public interface HttpRequest extends HttpMessage {
        HttpMethod getMethod();
        void setMethod(HttpMethod var1);
        String getUri();
        void setUri(String var1);
}

public interface HttpMessage {
        String getHeader(String var1);
        List<String> getHeaders(String var1);
        List<Entry<String, String>> getHeaders();
        boolean containsHeader(String var1);
        Set<String> getHeaderNames();
        HttpVersion getProtocolVersion();
        void setProtocolVersion(HttpVersion var1);
        ChannelBuffer getContent();
        void setContent(ChannelBuffer var1);
        void addHeader(String var1, Object var2);
        void setHeader(String var1, Object var2);
        void setHeader(String var1, Iterable<?> var2);
        void removeHeader(String var1);
        void clearHeaders();
        /** @deprecated */
        @Deprecated
        long getContentLength();
        /** @deprecated */
        @Deprecated
        long getContentLength(long var1);
        boolean isChunked();
        void setChunked(boolean var1);
        /** @deprecated */
        @Deprecated
        boolean isKeepAlive();
}

(4) com.sun.deploy.net.HttpRequest [not commonly used in Java]

public interface HttpRequest {
        String JNLP_MIME_TYPE = "application/x-java-jnlp-file";
        String ERROR_MIME_TYPE = "application/x-java-jnlp-error";
        String JAR_MIME_TYPE = "application/x-java-archive";
        String JAR_MIME_TYPE_EX = "application/java-archive";
        String PACK200_MIME_TYPE = "application/x-java-pack200";
        String JARDIFF_MIME_TYPE = "application/x-java-archive-diff";
        String GIF_MIME_TYPE = "image/gif";
        String JPEG_MIME_TYPE = "image/jpeg";
        String GZIP_ENCODING = "gzip";
        String PACK200_GZIP_ENCODING = "pack200-gzip";
        String CONTENT_ENCODING = "content-encoding";
        String CONTENT_LENGTH = "content-length";
        String ACCEPT_ENCODING = "accept-encoding";
        String CONTENT_TYPE = "content-type";
        String CONTENT_RANGE = "content-range";
        String CACHE_CONTROL = "cache-control";
        String LAST_MODIFIED = "last-modified";
        String EXPIRES = "expires";
        String DEPLOY_REQUEST_CONTENT_TYPE = "deploy-request-content-type";
        HttpResponse doGetRequestEX(URL var1, long var2) throws IOException;
        HttpResponse doGetRequestEX(URL var1, String[] var2, String[] var3, long var4) throws IOException;
        HttpResponse doHeadRequestEX(URL var1, long var2) throws IOException;
        HttpResponse doHeadRequestEX(URL var1, String[] var2, String[] var3, long var4) throws IOException;
        HttpResponse doHeadRequest(URL var1) throws IOException;
        HttpResponse doGetRequest(URL var1) throws IOException;
        HttpResponse doHeadRequest(URL var1, boolean var2) throws IOException;
        HttpResponse doGetRequest(URL var1, boolean var2) throws IOException;
        HttpResponse doHeadRequest(URL var1, String[] var2, String[] var3) throws IOException;
        HttpResponse doGetRequest(URL var1, String[] var2, String[] var3) throws IOException;
        HttpResponse doHeadRequest(URL var1, String[] var2, String[] var3, boolean var4) throws IOException;
        HttpResponse doGetRequest(URL var1, String[] var2, String[] var3, boolean var4) throws IOException;
}

2,HttpResponse

(1) org.apache.http.HttpResponse [not commonly used in Java]

public interface HttpResponse extends HttpMessage {
        StatusLine getStatusLine();
        void setStatusLine(StatusLine var1);
        void setStatusLine(ProtocolVersion var1, int var2);
        void setStatusLine(ProtocolVersion var1, int var2, String var3);
        void setStatusCode(int var1) throws IllegalStateException;
        void setReasonPhrase(String var1) throws IllegalStateException;
        HttpEntity getEntity();
        void setEntity(HttpEntity var1);
        Locale getLocale();
        void setLocale(Locale var1);
}

public interface HttpMessage {
        ProtocolVersion getProtocolVersion();
        boolean containsHeader(String var1);
        Header[] getHeaders(String var1);
        Header getFirstHeader(String var1);
        Header getLastHeader(String var1);
        Header[] getAllHeaders();
        void addHeader(Header var1);
        void addHeader(String var1, String var2);
        void setHeader(Header var1);
        void setHeader(String var1, String var2);
        void setHeaders(Header[] var1);
        void removeHeader(Header var1);
        void removeHeaders(String var1);
        HeaderIterator headerIterator();
        HeaderIterator headerIterator(String var1);
        /** @deprecated */
        @Deprecated
        HttpParams getParams();
        /** @deprecated */
        @Deprecated
        void setParams(HttpParams var1);
}

(2) org.jboss.netty.handler.codec.http.HttpResponse [not commonly used in Java]

public interface HttpResponse extends HttpMessage {
        HttpResponseStatus getStatus();
        void setStatus(HttpResponseStatus var1);
}

public interface HttpMessage {
        String getHeader(String var1);
        List<String> getHeaders(String var1);
        List<Entry<String, String>> getHeaders();
        boolean containsHeader(String var1);
        Set<String> getHeaderNames();
        HttpVersion getProtocolVersion();
        void setProtocolVersion(HttpVersion var1);
        ChannelBuffer getContent();
        void setContent(ChannelBuffer var1);
        void addHeader(String var1, Object var2);
        void setHeader(String var1, Object var2);
        void setHeader(String var1, Iterable<?> var2);
        void removeHeader(String var1);
        void clearHeaders();
        /** @deprecated */
        @Deprecated
        long getContentLength();
        /** @deprecated */
        @Deprecated
        long getContentLength(long var1);
        boolean isChunked();
        void setChunked(boolean var1);
        /** @deprecated */
        @Deprecated
        boolean isKeepAlive();
}

(3) com.sun.deploy.net.HttpResponse [not commonly used in Java]

public interface HttpResponse {
        URL getRequest();
        int getStatusCode();
        int getContentLength();
        long getExpiration();
        long getLastModified();
        String getContentType();
        String getResponseHeader(String var1);
        BufferedInputStream getInputStream();
        void disconnect();
        String getContentEncoding();
        MessageHeader getHeaders();
}

3. HttpServletRequest [commonly used in Java]
The HttpServletRequest object represents the client's request. When the client accesses the server through the HTTP protocol, all the information in the HTTP request header is encapsulated in this object. By the method provided by this object, all the information requested by the client can be obtained.

public interface HttpServletRequest extends ServletRequest {
        String BASIC_AUTH = "BASIC";
        String FORM_AUTH = "FORM";
        String CLIENT_CERT_AUTH = "CLIENT_CERT";
        String DIGEST_AUTH = "DIGEST";
        String getAuthType();
        Cookie[] getCookies();
        long getDateHeader(String var1);
        String getHeader(String var1);
        Enumeration<String> getHeaders(String var1);
        Enumeration<String> getHeaderNames();
        int getIntHeader(String var1);
        String getMethod();
        String getPathInfo();
        String getPathTranslated();
        String getContextPath();
        String getQueryString();
        String getRemoteUser();
        boolean isUserInRole(String var1);
        Principal getUserPrincipal();
        String getRequestedSessionId();
        String getRequestURI();
        StringBuffer getRequestURL();
        String getServletPath();
        HttpSession getSession(boolean var1);
        HttpSession getSession();
        String changeSessionId();
        boolean isRequestedSessionIdValid();
        boolean isRequestedSessionIdFromCookie();
        boolean isRequestedSessionIdFromURL();
        /** @deprecated */
        boolean isRequestedSessionIdFromUrl();
        boolean authenticate(HttpServletResponse var1) throws IOException, ServletException;
        void login(String var1, String var2) throws ServletException;
        void logout() throws ServletException;
        Collection<Part> getParts() throws IOException, ServletException;
        Part getPart(String var1) throws IOException, ServletException;
        <T extends HttpUpgradeHandler> T upgrade(Class<T> var1) throws IOException, ServletException;
}

public interface ServletRequest {
        Object getAttribute(String var1);
        Enumeration<String> getAttributeNames();
        String getCharacterEncoding();
        void setCharacterEncoding(String var1) throws UnsupportedEncodingException;
        int getContentLength();
        long getContentLengthLong();
        String getContentType();
        ServletInputStream getInputStream() throws IOException;
        String getParameter(String var1);
        Enumeration<String> getParameterNames();
        String[] getParameterValues(String var1);
        Map<String, String[]> getParameterMap();
        String getProtocol();
        String getScheme();
        String getServerName();
        int getServerPort();
        BufferedReader getReader() throws IOException;
        String getRemoteAddr();
        String getRemoteHost();
        void setAttribute(String var1, Object var2);
        void removeAttribute(String var1);
        Locale getLocale();
        Enumeration<Locale> getLocales();
        boolean isSecure();
        RequestDispatcher getRequestDispatcher(String var1);
        /** @deprecated */
        String getRealPath(String var1);
        int getRemotePort();
        String getLocalName();
        String getLocalAddr();
        int getLocalPort();
        ServletContext getServletContext();
        AsyncContext startAsync() throws IllegalStateException;
        AsyncContext startAsync(ServletRequest var1, ServletResponse var2) throws IllegalStateException;
        boolean isAsyncStarted();
        boolean isAsyncSupported();
        AsyncContext getAsyncContext();
        DispatcherType getDispatcherType();
}

4,HttpServletResponse
Servlet s are server-side programs that are mainly used to interactively browse and modify data to generate dynamic web content.
After the web server receives a Servlet request from the client, if it checks that an instance object of the Servlet has been loaded and created, it creates an HttpServletRequest object to encapsulate the HTTP request message and an HttpServletResponse object to represent the Http response message, then calls the service() method of the Servlet to pass the request and response object as parameters, whichThe sample client sends the request to the server through the HttpServletRequest object, and the server passes the response to the client through the HttpServletResponse object for communication purposes.

[Needless to say what the HttpServletResponse returns to the client, let's use HttpServletResponse to download the small demo file]
1. Upper Test File

/**
         * Download files, stream through OutputStream
         * @param response
         * @throws Exception
         */
        @GetMapping("/redant7")
        private void downloaduseHttpServletResponse(HttpServletResponse response) {
                try {
                        //1. File Name
                        String fileName = "2020 18 April 6, 2000:28:52.doc";
                        //2. Set the content-disposition response header to control the browser to open the file as a download
                        response.setHeader("content-disposition", "attachment;filename="+fileName);
                        //3. Get the file input stream to download
                        InputStream in = new FileInputStream("D:\\Frozen\\testFile\\frozen_redant_test.doc");
                        int len = 0;
                        //4. Create a data buffer
                        byte[] buffer = new byte[1024];
                        //5. Obtain OutputStream stream from response object
                        OutputStream out = response.getOutputStream();
                        //6. Write FileInputStream stream to buffer
                        while ((len = in.read(buffer)) > 0) {
                                //7. Use OutputStream to export buffer data to client browsers
                                out.write(buffer,0,len);
                        }
                        in.close();
                }catch (Exception e){
                        e.printStackTrace();
                }
        }

[HttpServletRequest and HttpServletResponse small demo]

@GetMapping("/redant5")
        public void getrequest(HttpServletRequest request,
                                                         HttpServletResponse response){
                /**
                 * 1.Get Client Information
                 * */
                try{
                        String requestUrl = request.getRequestURL().toString();//Get the requested URL address
                        String requestUri = request.getRequestURI();//Requested Resources
                        String queryString = request.getQueryString();//Get the parameters attached to the requested URL address
                        String remoteAddr = request.getRemoteAddr();//IP address of the visitor
                        String remoteHost = request.getRemoteHost();
                        int remotePort = request.getRemotePort();
                        String remoteUser = request.getRemoteUser();
                        String method = request.getMethod();//The method used to get the requested URL address
                        String pathInfo = request.getPathInfo();
                        String localAddr = request.getLocalAddr();//Get the IP address of the WEB server
                        String localName = request.getLocalName();//Get the hostname of the WEB server
                        response.setCharacterEncoding("UTF-8");//Set character output to client browser in UTF-8 encoding
                        //Control the browser's display of data in UTF-8 encoding by setting a response header. If you don't add this sentence, the browser will display garbled code
                        response.setHeader("content-type", "text/html;charset=UTF-8");
                        PrintWriter out = response.getWriter();
                        out.write("Client information is as follows:");
                        out.write("<hr/>");
                        out.write("Requested URL Address:"+requestUrl);
                        out.write("<br/>");
                        out.write("Requested resources:"+requestUri);
                        out.write("<br/>");
                        out.write("Requested URL Parameters attached to the address:"+queryString);
                        out.write("<br/>");
                        out.write("Visitor's IP Address:"+remoteAddr);
                        out.write("<br/>");
                        out.write("Host name of the visitor:"+remoteHost);
                        out.write("<br/>");
                        out.write("Port number used:"+remotePort);
                        out.write("<br/>");
                        out.write("remoteUser: "+remoteUser);
                        out.write("<br/>");
                        out.write("Method used in the request:"+method);
                        out.write("<br/>");
                        out.write("pathInfo: "+pathInfo);
                        out.write("<br/>");
                        out.write("localAddr: "+localAddr);
                        out.write("<br/>");
                        out.write("localName: "+localName);
                }catch (Exception e){
                        e.printStackTrace();
                }
        }

[ps return value using void has the same effect as returning String.]

@GetMapping("/redant6")
        public String getrequest6(HttpServletRequest request,
                                                     HttpServletResponse response){
                StringBuffer sb = new StringBuffer("Client information obtained is as follows:<hr/>");
                String requestUrl = request.getRequestURL().toString();//Get the requested URL address
                sb.append("Requested URL Address:"+requestUrl+"<br/>");
                String requestUri = request.getRequestURI();//Requested Resources
                sb.append("Requested resources:"+requestUri+"<br/>");
                String queryString = request.getQueryString();//Get the parameters attached to the requested URL address
                sb.append("Requested URL Parameters attached to the address:"+queryString+"<br/>");
                String remoteAddr = request.getRemoteAddr();//IP address of the visitor
                sb.append("Visitor's IP Address:"+remoteAddr+"<br/>");
                String remoteHost = request.getRemoteHost();
                sb.append("Host name of the visitor:"+remoteHost+"<br/>");
                int remotePort = request.getRemotePort();
                sb.append("Port number used:"+remotePort+"<br/>");
                String remoteUser = request.getRemoteUser();
                sb.append("remoteUser: "+remoteUser+"<br/>");
                String method = request.getMethod();//The method used to get the requested URL address
                sb.append("Method used in the request:"+method+"<br/>");
                String pathInfo = request.getPathInfo();
                sb.append("Detailed address:"+pathInfo+"<br/>");
                String localAddr = request.getLocalAddr();//Get the IP address of the WEB server
                sb.append("WEB Server's IP address:"+localAddr+"<br/>");
                String localName = request.getLocalName();//Get the hostname of the WEB server
                sb.append("WEB Host name of the server:"+localName+"<br/>");
                return sb.toString();
        }

Posted by only one on Mon, 06 Apr 2020 10:09:36 -0700