写了一个MyServer模拟http server 接收post请求。
java代码:
- Java code
package socket;import java.io.*;import java.net.*;public class MyServer { public static void main(String args[]) throws Exception{ ServerSocket serverSocket = new ServerSocket(8080); System.out.println("server is ok."); while(true){ Socket socket = serverSocket.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line = in.readLine(); while(line!=null){ System.out.println("Client: " + line); line = in.readLine(); } System.out.println("current user close the session."); in.close(); socket.close(); } }}
用浏览器打开下面的html文件,并提交数据:
- HTML code
<head> <title>test my server</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> <p>upload</p> <form name="UploadForm" method="post" action="http://localhost:8080/1.jsp"><input type="text" name="myname" /><br><select name="myage"> <option value="18">18</option> <option value="20">20</option> <option value="22">22</option></select><br><input type="submit"value="Sutmit"></form></body> </html>
MyServer打印出来的数据开始还正常:
server is ok.
Client: POST /testupload.jsp HTTP/1.1
Client: Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
Client: Referer: http://localhost:8080/post.html
Client: Accept-Language: zh-cn
Client: User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)
Client: Content-Type: application/x-www-form-urlencoded
Client: Accept-Encoding: gzip, deflate
Client: Host: localhost:8080
Client: Content-Length: 28
Client: Connection: Keep-Alive
Client: Cache-Control: no-cache
Client:
走到这里的时候, 按http协议,接下来浏览器该传送post的数据了,但是程序走到这里就不走了。当我按esc之后,post数据才被提交上去
Client: myname=wwwwwwwwwwww&myage=18
current user close the session.
很奇怪!
高手出来!
------解决方案--------------------
有两个问题:
1、因为你是readLine,最后的数据并没有回车换行,所以readLine就一直悬停了,你可以改成read(char[])这个方法试试,就能读到数据
2、你在读到数据后,应该向客户端发出应答,否则客户端不会关闭Socket(除非超时,可能很长),这样你的程序还是会挂在那里不退出。
------解决方案--------------------
并不奇怪,
readline要到文本行结尾才返回,
但post提交的数据通过http消息体发送,末尾不必加换车符,
所以此时readline就卡在那里了。
空行是http头和消息体的分隔,
可以在读到空行后,退出循环,转而用普通的读字符方式处理。
------解决方案--------------------
学习了
------解决方案--------------------
为什么不用 httpClient 呢? 已经封装好了的..
------解决方案--------------------
我晕,这都开始给学生讲课了啊,呵呵!
对于原始数据的Socket发送,一定不要用readLine,否则以后会出现很多编码字符上的误解!
------解决方案--------------------