JAVA用Socket模拟HTTP文件上传
2015-11-10 11:23
417 查看
根据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(); }
相关文章推荐
- java-模拟tomcat服务器
- Linux socket 初步
- RPC failed; result=22, HTTP code = 411
- HTTP Header 属性列表
- nginx中http核心模块的配置指令2
- nginx中http核心模块的配置指令3
- nginx中http核心模块的配置指令4
- nginx中http的fastcgi模块的配置指令1
- java socket 注意的地方
- java socket 注意的地方
- 如何在 Linux 中快速地通过 HTTP 提供文件访问服务
- 深入HTTP head的使用详解
- ASP 中使用 HTTP 协议发送参数详解
- C#基于socket模拟http请求的方法
- http www安全必备知识
- 简单的Ruby中的Socket编程教程
- Socket不能选择本地IP连接问题如何解决