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

/ 4,091评论 / 17428阅读 / 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. LarryHer说道:

    compare ed drugs: Canada pharmacy – best drugs for ed

  2. Looking for excitement? Aviator offers real-time decisions where you can win big or lose fast. Cash out before the plane flies away, or keep climbing to maximize winnings. Available with demo options for first-timers!

    play aviator online aviator real money game .

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

  4. сейфы说道:

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

  5. Jefferyswava说道:

    buying prescription drugs in mexico: mexican pharmacy online – pharmacies in mexico that ship to usa

  6. GlennSeade说道:

    natural remedies for ed Canada pharmacy causes for ed

  7. With huge multipliers and quick decision-making, Aviator has become a favorite among Indian online players. Use the demo to master your skills, then cash out in real money play before the plane flies away!

    aviator game for money aviator money game .

  8. Bradleyarrip说道:

    http://indianpharmacyeasy.com/# india pharmacy mail order

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

  10. LarryHer说道:

    mexican drugstore online: mexican pharmacy online – mexico drug stores pharmacies

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

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

  13. GlennSeade说道:

    mexican mail order pharmacies medicines mexico rx online best online pharmacies in mexico

  14. LarryHer说道:

    mexican border pharmacies shipping to usa: mexican drugstore online – mexico drug stores pharmacies

  15. Jefferyswava说道:

    buy prescription drugs online: canadian pharmacy – natural ed

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

  17. Jefferyswava说道:

    Online medicine home delivery: Best Indian pharmacy – indian pharmacy online

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

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

  20. It¦s really a great and helpful piece of info. I am happy that you just shared this useful info with us. Please keep us informed like this. Thank you for sharing.

  21. Jamiescact说道:

    https://indianpharmacyeasy.com/# indian pharmacy paypal

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

  23. GlennSeade说道:

    buying from online mexican pharmacy MexicanPharmGate buying prescription drugs in mexico online

  24. LarryHer说道:

    purple pharmacy mexico price list: medicines mexico rx online – mexican online pharmacies prescription drugs

  25. Jefferyswava说道:

    errection problems: canadian pharmacy – over the counter ed drugs

  26. Jamiescact说道:

    http://indianpharmacyeasy.com/# mail order pharmacy india

  27. aloetopakistan说道:

    Download 888Starz Bet and bet live on your favorite sports events.

  28. GlennSeade说道:

    cheap medications online canadiandrugsgate.com cvs prescription prices without insurance

  29. LarryHer说道:

    mail order pharmacy india: indianpharmacyeasy – india online pharmacy

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

  31. Jamiescact说道:

    https://indianpharmacyeasy.com/# best online pharmacy india

  32. profi-teh-remont说道:

    Сервисный центр предлагает замена дсплея acer ethos 5943g замена usb разъема acer ethos 5943g

  33. accepes说道:

    A liver biopsy showed steatosis, hepatocellular ballooning necrosis and mild cholestasis dapoxetina generico Destiny NREyYdOtwiSTA 5 21 2022

  34. profi-teh-remont说道:

    Сервисный центр предлагает ремонт hp pavilion 14-ba000 цены ремонт hp pavilion 14-ba000 в петербурге

  35. Jamiescact说道:

    http://canadiandrugsgate.com/# male erection pills

  36. Bradleyarrip说道:

    http://mexicanpharmgate.com/# mexico drug stores pharmacies

  37. Jamiescact说道:

    http://indianpharmacyeasy.com/# reputable indian pharmacies

  38. Jefferyswava说道:

    mexican rx online: mexican pharmacy online – mexican border pharmacies shipping to usa

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

  40. Jefferyswava说道:

    medication from mexico pharmacy: medicines mexico rx online – mexican mail order pharmacies

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

  42. Jamiescact说道:

    https://mexicanpharmgate.com/# buying prescription drugs in mexico

  43. LarryHer说道:

    best online pharmacies in mexico: mexican drugstore online – mexican rx online

  44. Bradleyarrip说道:

    https://canadiandrugsgate.com/# ed drugs compared

发表回复

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