c++ socket手写http multipart/form-data类型的post请求

版权所有,转载请注明出处

读取文件,保存为string

string FileToStr(string filepath) {
	fstream f(filepath, ios::in | ios::binary);
	if (f.good())
	{
		f.unsetf(ios::skipws); // 关闭inputFile的忽略空格标志,可以文件中的保留空格
		istream_iterator<char> iter(f);
		string s(iter, istream_iterator<char>());
		return s;
	}
	else
	{
		cout << "Can't open file!" << endl;
		return "";
	}
}

构造请求体

请求体里边包含了两个参数:“option”和“file”。

string file = FileToStr("test.mp4");
if (file == "") return -1;
string body = "--82ebdd74\r\n"
	"Content-Disposition: form-data; name=\"option\"\r\n\r\n"
	"1\r\n"
	"--82ebdd74\r\n"
	"Content-Disposition: form-data; name=\"file\"; filename=\"test.mp4\"\r\n"
	"Content-Type: video/mp4\r\n\r\n"
	+ file
	+ "--82ebdd74--\r\n\r\n";

构造请求头

string head = "POST /firespy/upload/ HTTP/1.1\r\n"
	"Host: 192.168.1.116:8000\r\n"  // url和host都是我用django在自己电脑上搭的服务端的地址
	"Accept: */*\r\n"
	"Accept-Encoding: gzip,deflate\r\n"
	"Accept-Language: zh-CN\r\n"
	"Content-Type: multipart/form-data; boundary=82ebdd74\r\n"  // boundary瞎写一个,别写太短就行,需要与请求体中保持一致
	"Content-Length: "+ to_string(body.length()) +"\r\n"  // 注意Content-Length一定不能算错
	"Connection: Keep-Alive\r\n\r\n";

发送请求

string str = head + body;
send(sock, str.c_str(), str.length() + 1, 0); // 需要事先绑定sock

完整代码就不放了,组合一块就行了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值