[HTTP/C++]请求体form-data解析

/ 4,094评论 / 17433阅读 / 11点赞

预备知识

URL编解码

请求体编码格式


form-data格式

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="myfile"; filename="hello.gif" filename*=UTF-8''hello.gif
Content-Type: image/gif


{二进制数据}
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="mytext"

coolight
------WebKitFormBoundary7MA4YWxkTrZu0gW--
--{boundary}(\r\n)
Content-Disposition: form-data; name="{key}"(\r\n)
(\r\n)
{value}(\r\n)
--{boundary}
--{boundary}(\r\n)
Content-Disposition: form-data; name="{key}"; filename="{filename}"(\r\n)[; filename*={编码方式}''{对应编码的filename}]
Content-Type: {文件格式}(\r\n)
(\r\n)
(\r\n)
{二进制数据}(\r\n)
--{boundary}

c++解析

这里使用正则表达式标准库匹配,并使用string_view减小开销。

#include <regex>
#include <string_view>
#include <map>

using std::string;
using std::multimap;
using std::string_view;

namespace mimicry {
	struct Http_form_data_s {
		bool isFile = false;	//是否为文件,否的话fileName和fileType是无效的
		//注意:fileName可能会包含./ ../等路径信息,此时可能会有一些危险的操作,建议截取最后一个/之后的文件名或自行命名
		std::string fileName;
		std::string fileName_CharEncoding;
		//有时可能文件名会乱码,因此请求中会有指定编码的文件名,对应字段 fileName*
		std::string fileName_;
		std::string fileType;
		std::string value;
	};

std::multimap<std::string, mimicry::Http_form_data_s>
read_form_data(const std::string& in_bound, const std::string& in_data) {
	std::multimap<std::string, mimicry::Http_form_data_s> remap;
	string_view view{ in_data };
	std::regex reg_name{"\\r\\nContent-Disposition:\\s*form-data;\\s*name=\"(.*)\"(?:\\s*;\\s*filename=\"(.*)\"(?:\\s*;\\s*filename\\*=(.*)''(.*))?\\r\\nContent-Type:\\s*(.*))?\\r\\n\\r\\n"};
	string find_bound = "--" + in_bound;
	mimicry::Http_form_data_s data;
	size_t pos = 0, pos_2 = 0;
	if ((pos = view.find(find_bound)) != string::npos) {
		pos += find_bound.size();
		for (;(pos_2 = view.find(find_bound, pos)) != string::npos;) {
			string_view block = view.substr(pos, pos_2 - pos);	//截取两个bound之间的内容
			std::match_results<string_view::const_iterator> block_match_view;
			if (std::regex_search(block.begin(), block.end(), block_match_view, reg_name)) {	//匹配 name 和可能存在的 filename
				data.fileName = block_match_view.str(2);
				data.fileName_CharEncoding = block_match_view.str(3);
				data.fileName_ = block_match_view.str(4);
				data.fileType = block_match_view.str(5);
				data.isFile = data.fileName.size() > 0;
				const char* str_p = &(* (block_match_view[0].second));
				size_t len = block.end() - 2 - block_match_view[0].second;
				//const string_view var_view = string_view{ block_match_view[0].second, block.end() - 2 };
				data.value = string(str_p, len);
				remap.insert({ block_match_view.str(1), data });
			}
			pos = pos_2 + find_bound.size();
		}
	}
	return remap;
}
};

其他

boundary的来历

form-data和Birnary的选择

  1. Great tremendous things here. I am very happy to see your article. Thanks a lot and i’m taking a look ahead to touch you. Will you please drop me a e-mail?

  2. Тут можно преобрести сейфы пожаростойкие огнеупорный сейф

  3. Jamiescact说道:

    https://mexicanpharmgate.com/# п»їbest mexican online pharmacies

  4. LarryHer说道:

    male ed drugs: Best Canadian online pharmacy – drugs that cause ed

  5. GlennSeade说道:

    mexico drug stores pharmacies mexican pharmacy buying prescription drugs in mexico

  6. Bradleyarrip说道:

    http://canadiandrugsgate.com/# online canadian drugstore

  7. Jamiescact说道:

    https://mexicanpharmgate.com/# pharmacies in mexico that ship to usa

  8. Jefferyswava说道:

    mexico drug stores pharmacies: mexican pharmacy online medications – medication from mexico pharmacy

  9. Jefferyswava说道:

    Online medicine home delivery: Indian pharmacy international shipping – best india pharmacy

  10. Тут можно преобрести сейф под ружье купить купить сейф оружейный в москве

  11. Bradleyarrip说道:

    http://mexicanpharmgate.com/# purple pharmacy mexico price list

  12. Тут можно преобрести огнестойкий сейф сейф огнестойкий

  13. Тут можно преобрести купить сейф для ружья в интернет магазине пистолетные сейфы москва

  14. Тут можно преобрести сейф огнестойкий купить сейф огнестойкий цена

  15. For players seeking an intense gaming experience, Aviator offers just that. Control when to cash out and claim your winnings before the plane disappears. Indian players love the demo mode for practicing their timing.

    aviator real money game aviator game online .

  16. Тут можно преобрести купить огнестойкий сейф сейф несгораемый купить

  17. profi-teh-remont说道:

    Сервисный центр предлагает ремонт samsung rv408 в петербурге ремонт samsung rv408 в петербурге

  18. CurtisTraup说道:

    ED meds online buy ed pills cheapest ed pills ere pharm

  19. RobertCaw说道:

    buy ed pills: ere pharm – erepharm pills

  20. Тут можно преобрести несгораемый сейф огнестойкие сейфы цена

  21. CurtisTraup说道:

    ED meds online erepharm pills ED meds online

  22. Lloydlania说道:

    https://kampharm.shop/# kamagra oral jelly

  23. DennisBob说道:

    gabapentin: Buy gabapentin for humans – Buy gabapentin for humans

  24. DennisBob说道:

    GabaPharm: buy gabapentin online – buy gabapentin india

  25. The Aviator game is a favorite among Indian players for its real-time betting and intense strategy. Choose to play for real money or try the demo mode to learn the mechanics risk-free. It’s all about when you pull the trigger!

    aviator game for money aviator money game .

  26. LesleyBling说道:

    оценка условий труда на производстве аттестация соут

  27. CurtisTraup说道:

    furpharm fur pharm furosemide fur pharm

  28. Some really nice stuff on this website , I enjoy it.

  29. CurtisTraup说道:

    GabaPharm Gabapentin Buy gabapentin for humans gabapentin GabaPharm

  30. Тут можно преобрести несгораемые сейфы сейф пожаростойкий

  31. Lloydlania说道:

    http://kampharm.shop/# kampharm.shop

  32. DennisBob说道:

    buy rybelsus canada: rybpharm cheap semaglutide – semaglutide

  33. RobertCaw说道:

    rybpharm canada: rybpharm cheap semaglutide – buy rybelsus online usa

  34. DennisBob说道:

    rybpharm canada: rybpharm cheap semaglutide – buy rybelsus rybpharm

  35. Тут можно преобрести купить сейф для охотничьего ружья сейф для оружия в москве

  36. Robertmep说道:

    https://gabapharm.com/# cheapest Gabapentin GabaPharm

  37. Lloydlania说道:

    https://rybpharm.com/# buy rybelsus rybpharm

  38. CurtisTraup说道:

    rybpharm rybelsus rybpharm canada rybpharm

  39. Здесь можно преобрести сейф купить в москве модели сейфов

  40. DennisBob说道:

    kampharm shop: kam pharm shop – buy kamagra oral jelly Kam Pharm

  41. Lloydlania说道:

    https://kampharm.shop/# cheapest Kamagra Kam Pharm

  42. Здесь можно преобрести сейфы москва где купить сейфы в москве

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注