Http与Servlet
什么是HTTP?
HTTP协议(HyperText Transfer Protocol,超文本传输协议)是因特网上应用最为广泛的一种网络传输协议,所有的WWW文件都必须遵守这个标准。
HTTP是一个基于TCP/IP通信协议来传递数据(HTML 文件, 图片文件, 查询结果等)。
HTTP的设计目的是保证客户机与服务器之间的通信,统一了服务端与客户端信息传输的格式。
具体可看:http://www.runoob.com/http/http-intro.html
GET方法
要求得到所请求URL上的一个东西(资源/文件)。
浏览器访问网站时,如果发送的请求是GET请求,URL便是GET请求的内容。例如:/test/demo_form.asp?name1=value1&name2=value2
实例:
GET /job/zw.asp HTTP/1.1
Host: www.qufu123.com
Upgrade-Insecure-Requests: 1
User-Agent: <删去5毛>
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Referer: http://www.qufu123.com/
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
Cookie: <删去5毛>
Connection: close
POST方法
要求服务器接收附加到请求的体信息,并提供所请求URL上的一个东西。这像是一个扩展的GET……也就是说,随请求还发送了额外信息的“GET”,不过与GET不同的是,它的体信息在请求首部的后面,而GET是追加上URL后面的。
实例:
POST /user/api/user.api.asp?act=login HTTP/1.1
Host: www.qufu123.com
Content-Length: 35
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://www.qufu123.com
X-Requested-With: XMLHttpRequest
User-Agent: <删去5毛>
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://www.qufu123.com/login.asp
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
Cookie: <删去5毛>
Connection: close
username=value1&password=value2&logined=1
Servlet处理GET、POST
public class Download extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("image/png");
var file = new File("D:\\a.png");
response.addHeader("Content-Disposition","attachment;filename="
+ new String("a.png".getBytes("GBK"),"ISO8859_1"));
response.addHeader("Content-Length","" + file.length());
download(response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
private void download(OutputStream out) throws IOException {
var bis = new BufferedInputStream(new FileInputStream("D:\\a.png"));
var bos = new BufferedOutputStream(out);
int read;
byte[] buffer = new byte[1024];
while ((read = bis.read(buffer, 0, 1024)) > 0) {
bos.write(buffer, 0, read);
}
bis.close();
bos.flush();
bos.close();
}
}