您的位置:首页 > 理论基础 > 计算机网络

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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  http socket