JAVA用Socket模拟HTTP文件上传

根据RFC1867协议模拟HTTP文件上传

try {
            String host = "127.0.0.1";
            int port = 8080;
            Socket socket = new Socket(host,port);
            StringBuffer buffer = new StringBuffer();
            //要上传的文件
            File file = new File("D:/IMG_1445.jpg");
            //分割标识 可以随机生成任意字符串
            String boundary = "----WebKitFormBoundarybRVyo9rDBLarLpgo";
            StringBuffer fileHead = new StringBuffer();
            //body结束 --boundary--\r\n   最后要加上换行符
            String bodyEnd = "\r\n--" + boundary + "--\r\n";
            fileHead.append("--" + boundary + "\r\n");
            //文件上传head
            fileHead.append("Content-Disposition: form-data; name=\"uploadFile\"; filename=\""+file.getName()+"\"\r\n");
            // fileHead.append("Content-Type: image/jpeg\r\n"); //不传服务器一样能接收
            fileHead.append("\r\n");
            //计算Content-Length  如果不传或算不正确服务器端接受的数据则会出错
            long length = fileHead.toString().getBytes().length + file.length()
                    + bodyEnd.getBytes().length;
            buffer.append("POST http://localhost:8080/Ftp/upload HTTP/1.1\r\n");
            buffer.append("Host: localhost:8080\r\n");
            buffer.append("UserAgent: IE8.0\r\n");
            // buffer.append("Connection: Keep-Alive\r\n"); //请求完后tcp连接不会中断直至超时
            buffer.append("Connection: close\r\n"); //请求完后tcp连接直接中断
            buffer.append("Content-Length: " + length + "\r\n");
            buffer.append("Content-Type: multipart/form-data; boundary="+boundary+"\r\n");
            buffer.append("\r\n");
            //这里开始计算body长度
            buffer.append(fileHead);

            socket.getOutputStream().write(buffer.toString().getBytes());
            // Thread.sleep(10000);
            FileInputStream fis = new FileInputStream(file);
            byte[] bs = new byte[512];
            int len = -1;
            while ((len = fis.read(bs)) != -1) {
                socket.getOutputStream().write(bs,0,len);
            }
            socket.getOutputStream().write(bodyEnd.getBytes());

            // --输出服务器传回的消息的头信息
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值