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

/ 4,109评论 / 17476阅读 / 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. CarrollWip说道:

    deneme bonusu veren siteler yeni https://denemebonusuverensiteler.top/# deneme bonusu veren siteler

  2. LarryBow说道:

    ultrabet bonus ultrabet tr online ultrabet

  3. HassanMesty说道:

    https://casinositeleri.win/# Casino Siteleri
    deneme bonusu veren siteler denemebonusu2026.com

  4. ClydeTal说道:

    en kazancl? slot oyunlar?: az parayla cok kazandiran slot oyunlar? – slot oyunlar? puf noktalar?

  5. accepes说道:

    priligy dosage Filiberto zDEEJYWpKICWjYKFAn 6 4 2022

  6. CarrollWip说道:

    deneme bonusu veren siteler https://casinositeleri.win/# casino siteleri win

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

  8. LarryBow说道:

    guvenilir casino siteleri Canl? Casino Siteleri Deneme Bonusu Veren Siteler

  9. HassanMesty说道:

    https://matadorbet.bid/# matadorbet giris
    deneme bonusu veren siteler betturkey betturkey.com

  10. onexslotsfun说道:

    Хотите начать игру? Скачайте 1xslots на андроид бесплатно и получите доступ к бонусам.

  11. Dereknef说道:

    ultrabet: ultrabet bonus – ultrabet yeni giris 1125

  12. CarrollWip说道:

    deneme bonusu veren siteler https://casinositeleri.win/# Casino Siteleri

  13. ClydeTal说道:

    deneme bonusu veren siteler: deneme bonusu veren siteler – deneme bonusu veren siteler betturkey

  14. Dereknef说道:

    casino siteleri win: Casino Siteleri – casino siteleri win

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

  16. LarryBow说道:

    matadorbet bid matadorbet.bid matadorbet giris

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

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

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

  20. Williambiz说道:

    pet antibiotics without vet prescription http://pharm24.pro/# how to help ed

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

  22. JorgeSEk说道:

    cheap erectile dysfunction pills online: low cost pharmacy – ed drugs list

  23. BrandonGak说道:

    india online pharmacy: Order medicine from India to USA – india online pharmacy

  24. DevonStolf说道:

    https://indianpharm24.pro/# indian pharmacies safe
    dysfunction erectile

  25. Williambiz说道:

    buy generic ed pills online https://indianpharm24.pro/# Online medicine order

  26. DevonStolf说道:

    http://pharm24.pro/# ed clinics
    male erection

  27. JorgeSEk说道:

    mexican mail order pharmacies: Legit online Mexican pharmacy – buying prescription drugs in mexico

  28. DavidKit说道:

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

  29. Williambiz说道:

    pumps for ed http://pharm24.pro/# buy prescription drugs without doctor

  30. JorgeSEk说道:

    mexican border pharmacies shipping to usa: mexican pharmacy – п»їbest mexican online pharmacies

  31. DevonStolf说道:

    http://indianpharm24.pro/# Online medicine order
    dog antibiotics without vet prescription

  32. Williambiz说道:

    diabetes and ed https://mexicanpharm24.cheap/# buying from online mexican pharmacy

  33. BrandonGak说道:

    Online medicine home delivery: India pharmacy international – reputable indian pharmacies

  34. DevonStolf说道:

    http://indianpharm24.pro/# indian pharmacy
    ed drugs online

  35. JorgeSEk说道:

    over the counter ed remedies: low cost prescription – ed medications online

  36. Williambiz说道:

    buy online pharmacy http://indianpharm24.pro/# world pharmacy india

  37. DevonStolf说道:

    https://indianpharm24.pro/# reputable indian pharmacies
    viagra without a doctor prescription walmart

  38. JorgeSEk说道:

    top rated ed pills: cheap pharmacy online – prescription drugs

  39. Williambiz说道:

    the canadian drugstore http://indianpharm24.pro/# best online pharmacy india

  40. BrandonGak说道:

    ed pumps: cheap medication – legal to buy prescription drugs without prescription

  41. Leroytrupt说道:

    pharmacies in mexico that ship to usa mexico pharmacy mexican drugstore online

  42. Leroytrupt说道:

    mexican online pharmacies prescription drugs Mexican pharmacy ship US medication from mexico pharmacy

  43. Leroytrupt说道:

    viagra without a prescription cheap meds best ed solution

  44. Williambiz说道:

    ed treatment natural https://indianpharm24.pro/# top online pharmacy india

  45. BrandonGak说道:

    mexican mail order pharmacies: Mexican pharmacy ship US – buying from online mexican pharmacy

  46. JorgeSEk说道:

    best online pharmacy india: medicines from India – indian pharmacy

  47. Leroytrupt说道:

    medication from mexico pharmacy mexican pharmacy mexican rx online

  48. DevonStolf说道:

    http://mexicanpharm24.cheap/# medication from mexico pharmacy
    buy online pharmacy

发表回复

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