【四种情况】:
HttpRequest、HttpResponse、HttpServletRequest、HttpServletResponse
【什么是HTTP?】
超文本传输协议(HyperText Transfer Protocol -- HTTP)是一个设计来使客户端和服务器顺利进行通讯的协议。
HTTP在客户端和服务器之间以request-response protocol(请求-回复协议)工作。
【Http常用的两个方法】
get - 从指定的服务器中获取数据
post - 提交数据给指定的服务器处理
【GET方法】
使用GET方法时,查询字符串(键值对)被附加在URL地址后面一起发送到服务器:
/test/demo_form.jsp?name1=value1&name2=value2
特点:
A、请求能够被缓存
B、请求会保存在浏览器的历史记录中
C、Url能够保存为浏览器书签
D、请求有长度限制【参数带入几十个Id,会发现少参数了】
E、get就是查询嘛,主要用来获取数据
【POST方法:】
使用POST方法时,查询字符串在POST信息中单独存在,和HTTP请求一起发送到服务器:
POST /test/demo_form.jsp HTTP/1.1
Host: w3schools.com
name1=value1&name2=value2
特点:
A、请求不能保存缓存
B、请求不能存为浏览器历史记录
C、请求无法存书签
D、长度无限制【因此,多数据的东西都通post以form表单的形式提交】
方式 | 描述 |
---|---|
HEAD | 与GET请求类似,不同在与服务器只返回HTTP头部信息,没有页面内容 |
PUT | 上传指定URL的描述 |
DELETE | 删除指定资源 |
OPTIONS | 返回服务器支持的HTTP方法 |
CONNECT | 转换为透明TCP/IP隧道的连接请求 |
1、HttpRequest
①org.apache.http.HttpRequest处理标题Header相关[Java不常用]
从接口org.apache.http继承的方法,HttpMessage,包括:
【1】void addHeader(Header header)
向此消息添加标题。
【2】void addHeader(String name, String value)
向此消息添加标题。
【3】boolean containsHeader(String name)
检查此消息中是否存在某些头。
【4】Header[] getAllHeaders()
返回此消息的所有标头。
【5】Header getFirstHeader(String name)
返回带有此消息的指定名称的第一个标头。
【6】Header[] getHeaders(String name)
返回具有此消息的指定名称的所有标头。
【7】Header getLastHeader(String name)
返回带有此消息的指定名称的最后一个标头。
【8】HttpParams getParams()
不推荐使用。 使用提供的配置类“ org.apache.http.config”和“ org.apache.http.client.config”
【9】ProtocolVersion getProtocolVersion()
返回此消息兼容的协议版本。
【10】HeaderIterator headerIterator()
返回所有标头的迭代器。
【11】HeaderIterator headerIterator(String name)
返回具有给定名称的标头的迭代器。
【12】void removeHeader(Header header)
从此消息中删除标题。
【13】void removeHeaders(String name)
从此消息中删除所有具有特定名称的标头。
【14】void setHeader(Header header)
用相同的名称覆盖第一个标头。
【15】void setHeader(String name, String value)
用相同的名称覆盖第一个标头。
【16】void setHeaders(Header[] headers)
覆盖邮件中的所有标题。
【17】void setParams(HttpParams params)
不推荐使用。 使用提供的配置类“ org.apache.http.config”和“ 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);
}
②org.springframework.http.HttpRequest获取URI[Java不常用]
public interface HttpRequest extends HttpMessage {
@Nullable
default HttpMethod getMethod() {
return HttpMethod.resolve(this.getMethodValue());
}
String getMethodValue();
URI getURI();
}
public interface HttpMessage {
HttpHeaders getHeaders();
}
③org.jboss.netty.handler.codec.http.HttpRequest[Java不常用]
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();
}
④com.sun.deploy.net.HttpRequest[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
①org.apache.http.HttpResponse[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);
}
②org.jboss.netty.handler.codec.http.HttpResponse[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();
}
③com.sun.deploy.net.HttpResponse[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[Java常用]
HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求头中的所有信息都封装在这个对象中,通过这个对象提供的方法,可以获得客户端请求的所有信息。
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是服务器端程序,主要用来交互式地浏览和修改数据,生成动态web内容。
web服务器接收到客户端的Servlet请求后,如果检查到已经装载并创建了该Servlet的实例对象,则会创建一个用于封装HTTP请求消息的HttpServletRequest对象和一个代表Http响应消息的HttpServletResponse对象,然后调用Servlet的service()方法,将请求和响应对象作为参数传递进去,这样客户端通过HttpServletRequest对象将请求发送给服务器,服务器通过HttpServletResponse对象将响应传递给客户端,达到通信的目的。
【HttpServletResponse向客户端返回消息什么的自不必说,现在咱们来用HttpServletResponse实现下载文件小 demo】
1、上测试文件
/**
* 下载文件,通过OutputStream流
* @param response
* @throws Exception
*/
@GetMapping("/redant7")
private void downloaduseHttpServletResponse(HttpServletResponse response) {
try {
//1、文件名
String fileName = "2020年4月6日18:28:52.doc";
//2.设置content-disposition响应头控制浏览器以下载的形式打开文件
response.setHeader("content-disposition", "attachment;filename="+fileName);
//3.获取要下载的文件输入流
InputStream in = new FileInputStream("D:\\Frozen\\testFile\\frozen_redant_test.doc");
int len = 0;
//4.创建数据缓冲区
byte[] buffer = new byte[1024];
//5.通过response对象获取OutputStream流
OutputStream out = response.getOutputStream();
//6.将FileInputStream流写入到buffer缓冲区
while ((len = in.read(buffer)) > 0) {
//7.使用OutputStream将缓冲区的数据输出到客户端浏览器
out.write(buffer,0,len);
}
in.close();
}catch (Exception e){
e.printStackTrace();
}
}
【HttpServletRequest与HttpServletResponse小 demo】
@GetMapping("/redant5")
public void getrequest(HttpServletRequest request,
HttpServletResponse response){
/**
* 1.获得客户机信息
* */
try{
String requestUrl = request.getRequestURL().toString();//得到请求的URL地址
String requestUri = request.getRequestURI();//得到请求的资源
String queryString = request.getQueryString();//得到请求的URL地址中附带的参数
String remoteAddr = request.getRemoteAddr();//得到来访者的IP地址
String remoteHost = request.getRemoteHost();
int remotePort = request.getRemotePort();
String remoteUser = request.getRemoteUser();
String method = request.getMethod();//得到请求URL地址时使用的方法
String pathInfo = request.getPathInfo();
String localAddr = request.getLocalAddr();//获取WEB服务器的IP地址
String localName = request.getLocalName();//获取WEB服务器的主机名
response.setCharacterEncoding("UTF-8");//设置将字符以"UTF-8"编码输出到客户端浏览器
//通过设置响应头控制浏览器以UTF-8的编码显示数据,如果不加这句话,那么浏览器显示的将是乱码
response.setHeader("content-type", "text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.write("客户机信息如下:");
out.write("<hr/>");
out.write("请求的URL地址:"+requestUrl);
out.write("<br/>");
out.write("请求的资源:"+requestUri);
out.write("<br/>");
out.write("请求的URL地址中附带的参数:"+queryString);
out.write("<br/>");
out.write("来访者的IP地址:"+remoteAddr);
out.write("<br/>");
out.write("来访者的主机名:"+remoteHost);
out.write("<br/>");
out.write("使用的端口号:"+remotePort);
out.write("<br/>");
out.write("remoteUser:"+remoteUser);
out.write("<br/>");
out.write("请求使用的方法:"+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 返回值使用void与返回String效果是一样的。】
@GetMapping("/redant6")
public String getrequest6(HttpServletRequest request,
HttpServletResponse response){
StringBuffer sb = new StringBuffer("获取到的客户机信息如下:<hr/>");
String requestUrl = request.getRequestURL().toString();//得到请求的URL地址
sb.append("请求的URL地址:"+requestUrl+"<br/>");
String requestUri = request.getRequestURI();//得到请求的资源
sb.append("请求的资源:"+requestUri+"<br/>");
String queryString = request.getQueryString();//得到请求的URL地址中附带的参数
sb.append("请求的URL地址中附带的参数:"+queryString+"<br/>");
String remoteAddr = request.getRemoteAddr();//得到来访者的IP地址
sb.append("来访者的IP地址:"+remoteAddr+"<br/>");
String remoteHost = request.getRemoteHost();
sb.append("来访者的主机名:"+remoteHost+"<br/>");
int remotePort = request.getRemotePort();
sb.append("使用的端口号:"+remotePort+"<br/>");
String remoteUser = request.getRemoteUser();
sb.append("remoteUser:"+remoteUser+"<br/>");
String method = request.getMethod();//得到请求URL地址时使用的方法
sb.append("请求使用的方法:"+method+"<br/>");
String pathInfo = request.getPathInfo();
sb.append("详细地址:"+pathInfo+"<br/>");
String localAddr = request.getLocalAddr();//获取WEB服务器的IP地址
sb.append("WEB服务器的IP地址:"+localAddr+"<br/>");
String localName = request.getLocalName();//获取WEB服务器的主机名
sb.append("WEB服务器的主机名:"+localName+"<br/>");
return sb.toString();
}
原文地址:https://blog.51cto.com/13479739/2485166