HTTP请求消息
1、http请求报文格式解析:起始行+首部字段+主体
POST /api/feed/ HTTP/1.1 –起始行
Accept-Encoding: gzip –请求头
Content-Length: 225873
Content-Type: multipart/form-data; boundary=OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp
Host: www.myhost.com
Connection: Keep-Alive
(以下请求正文)
–OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp –分隔符
Content-Disposition: form-data; name=”lng” –参数
Content-Type: text/plain; charset=UTF-8 –(说明是文本)
Content-Transfer-Encoding: 8bit
–空行
116.361545 参数值
–OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp
Content-Disposition: form-data; name=”lat”
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
39.979006
–OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp
Content-Disposition: form-data; name=”images”; filename=”/storage/emulated/0/Camera/jdimage/1xh0e3yyfmpr2e35tdowbavrx.jpg”
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
这里是图片的二进制数据
–OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp–
2、http响应报文格式解析
HTTP/1.1 200 OK
Date: Sun, 08 Jan 2017 08:24:23 GMT
Content-Type: text/html;charset=UTF-8
Content-Length: 908
resp{
errmsg=操作成功
errno=0
}
进入正题
1、模拟http服务器
package http;
import java.io.IOException;
import java.net.ServerSocket;
/**
* Created by 蓝师傅 on 2017/1/7.
*/
public class SimpleHttpServer extends Thread {
//端口号
public static final int HTTP_PORT = 8005;
ServerSocket mSocket = null;
public SimpleHttpServer(){
try {
mSocket = new ServerSocket(HTTP_PORT);
} catch (IOException e) {
throw new RuntimeException("服务器socket初始化失败");
}
}
@Override
public void run() {
//等待客户端连接
try {
while (true){
System.out.println("等待连接.....");
//这里会一直阻塞,知道有socket连接进来
//一旦客户端连接,拿到socket对象,交给DeliverThread 处理
new DeliverThread(mSocket.accept()).start();
}