java socket解析http消息 GET/POST 携带单个附件

这是一个Java实现的简单HTTP服务器,可以处理GET和POST请求,特别是能解析携带单个附件的POST请求。通过读取HTTP头部信息,服务器能识别并保存上传的文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package socket;

import java.io.*;
import java.net.*;
/**
 * MyHttpServer 实现一个简单的HTTP服务器端,可以获取用户提交的内容
 * 并给用户一个response
 * 因为时间的关系,对http头的处理显得不规范
 * 对于上传附件,暂时只能解析只上传一个附件而且附件位置在第一个的情况
  * **/
public class MyHttpServer {
    //服务器根目录,post.html, upload.html都放在该位置
    public static String WEB_ROOT = "c:/root";
    //端口
    private int port;
    //用户请求的文件的url
    private String requestPath;
    //mltipart/form-data方式提交post的分隔符,
    private String boundary = null;
    //post提交请求的正文的长度
    private int contentLength = 0;

    public MyHttpServer(String root, int port) {
        WEB_ROOT = root;
        this.port = port;
        requestPath = null;
    }
    //处理GET请求
    private void doGet(DataInputStream reader, OutputStream out) throws Exception {
        if (new File(WEB_ROOT + this.requestPath).exists()) {
            //从服务器根目录下找到用户请求的文件并发送回浏览器
            InputStream fileIn = new FileInputStream(WEB_ROOT + this.requestPath);
            byte[] buf = new byte[fileIn.available()];
            fileIn.read(buf);
            out.write(buf);
            out.close();
            fileIn.close();
            reader.close();
            System.out.println("request complete.");
        }
    }
    //处理post请求
    private void doPost(DataInputStream reader, OutputStream out) throws Exception {
        String line = reader.readLine();
        while (line != null) {
            System.out.println(line);
            line = reader.readLine();
            if ("".equals(line)) {
                break;
            } else if (line.indexOf("Content-Length") != -1) {
                this.contentLength = Integer.parseInt(line.substring(line.indexOf("Content-Length") + 16));
            }
            //表明要上传附件, 跳转到doMultiPart方法。
            else if(line.index

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值