http之HttpServletRequest和HttpServletResponse
对于客户端的一个请求,服务端建立request和response对象,分别代表请求和返回。
一、HttpServletRequest对象
客户端通过http协议访问时,请求中所有的信息都存放在该对象中,包括parameter name和value,attribute,
input stream,cookie,http协议相关的信息等。
1、parameter和attribute的区别
parameter是客户端提交的参数;
attribute是与客户端无关,在不同servlet之间传递参数,当做容器使用
设置:
String white = (String) request.setAttribute(“name”,"china");
读取:
String white = (String) request.getAttribute(“name”);
2、Cookie
Cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client).
cookie是当做http头部信息存储k-v形式存储,key固定为Cookie,v为name=value形式,多个键值以分号分割。
服务端读取cookie
//简便的获取cookie信息的方式 Cookie[] cookies = request.getCookies(); for(Cookie cookie : cookies){ log.info("name={},value={}",cookie.getName(),cookie.getValue()); } //原始的从头部获取cookie的方式 String rawCookie = request.getHeader("Cookie"); String[] rawCookieParams = rawCookie.split(";"); for(String cookie : rawCookieParams){ log.info("cookie={}",cookie); }
参考:
https://*.com/questions/33690741/httpservletrequest-getcookies-or-getheader
3、inputStream
ServletInputStream servletInputStream = request.getInputStream();
参考JAVA API解释
可以看出为客户端请求的字节流,一般框架已经封装好,使用较少。
public abstract class ServletInputStream extends InputStream
readLine
method for reading data one line at a time. With some protocols, such as HTTP POST and PUT, a ServletInputStream
object can be used to read data sent from the client.
A ServletInputStream
object is normally retrieved via the ServletRequest.getInputStream()
method.
This is an abstract class that a servlet container implements. Subclasses of this class must implement the java.io.InputStream.read()
method.
二、HttpServletReponse对象
//设置http返回码:404、200等 resp.setStatus(HttpServletResponse.SC_NOT_FOUND); resp.setContentType("application/json;charset=UTF-8"); String data = "这是字节流输出的内容"; byte[] dataByteArr = data.getBytes(StandardCharsets.UTF_8); //获取http输出字节流 //resp.getOutputStream().write(dataByteArr); //resp.flushBuffer(); //获取http输出字符流 resp.getWriter().println("这是字符流输出的内容");
获取字节流还是字符流只能选择一种。
上一篇: git之tag的使用
下一篇: http之常用客户端
推荐阅读
-
javaWeb核心技术第七篇之HTTP、Tomcat、Servlet、Request和Response
-
wicket获得原始的HttpServletRequest 和HttpServletResponse
-
python网络爬虫进阶之HTTP原理,爬虫的基本原理,Cookies和代理介绍
-
Nodejs核心模块之net和http的使用详解
-
现有web系统替换成Spring Boot2框架 之21 同时支持带项目名和不带项目名访问,web访问强制https,接口保持http访问 Spring Boot2带项目名不带项目名httpshttp
-
(JavaWeb)HttpServletResponse和HttpServletRequest
-
HttpServletResponse和HttpServletRequest
-
HttpServletRequest和HttpServletResponse
-
HttpServletResponse和HTTPServletRequest
-
HttpServletRequest和HttpServletResponse