Java:请求Servlet,为什么数据长度显示-1呢


   
  public class Test extends HttpServlet {
  
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getParameter("line"));
int len = request.getContentLength();
System.out.println("len:"+len);
}
}

请求URL:

   
  http://localhost:8090/Example/servlet/Test?line=Winner
 

输出结果:

   
  Winner
  
len:-1

数据都已经接收到了,为什么数据长度是-1呢?

java servlet

killuag 10 years, 2 months ago

我理解是说, HTTP GET请求是没有 Content的, GET请求大概张这个样子:

   
  GET http://localhost/Blabla HTTP/1.1
  
Accept: text/css
Accept-Language: en-US
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
DNT: 1
Cookie: JSESSIONID=FSDFAFWE233T3344T24FG4F42424R34R

而HTTP POST是有content的, Header里有Content-Length这个值.

   
  POST http://localhost/blabla HTTP/1.1
  
Accept: */*
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Connection: Keep-Alive
Content-Length: 28
JSESSIONID=nLHpSPGfJyYpNJmHv8spG7NPdhCqPB0Y7ySHBnH6pcGbBclpn06S!-697632674

data1=fadfasdfa&data2=dfasdfasd

请用doPost()试一下.

这该死的昵称 answered 10 years, 2 months ago

Your Answer