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

/ 4,112评论 / 17496阅读 / 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. JorgeSEk说道:

    india pharmacy mail order: medicines from India – buy prescription drugs from india

  2. Williambiz说道:

    how to overcome ed https://indianpharm24.pro/# indian pharmacy

  3. Leroytrupt说道:

    cheapest online pharmacy india India pharmacy international best india pharmacy

  4. GU10 LED bulb说道:

    I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post…

  5. DevonStolf说道:

    http://mexicanpharm24.cheap/# mexican drugstore online
    top erection pills

  6. BrandonGak说道:

    п»їbest mexican online pharmacies: mexico pharmacy – pharmacies in mexico that ship to usa

  7. Leroytrupt说道:

    mexican mail order pharmacies mexico pharmacy reputable mexican pharmacies online

  8. Williambiz说道:

    ed medicine online http://mexicanpharm24.cheap/# buying prescription drugs in mexico online

  9. JorgeSEk说道:

    online pharmacy india: Indian pharmacy worldwide delivery – online shopping pharmacy india

  10. DevonStolf说道:

    http://pharm24.pro/# online meds for ed
    best ed supplements

  11. Williambiz说道:

    male dysfunction treatment http://indianpharm24.pro/# top 10 online pharmacy in india

  12. JorgeSEk说道:

    medication from mexico pharmacy: mexican pharm 24 – mexican mail order pharmacies

  13. BrandonGak说道:

    best price for generic viagra on the internet: low cost prescription – medication for ed

  14. DevonStolf说道:

    http://mexicanpharm24.cheap/# buying prescription drugs in mexico online
    male erection

  15. Leroytrupt说道:

    reputable indian pharmacies medicines from India reputable indian online pharmacy

  16. Williambiz说道:

    ed meds online without doctor prescription http://indianpharm24.pro/# indianpharmacy com

  17. Leroytrupt说道:

    mexican online pharmacies prescription drugs mexico pharmacy mexican mail order pharmacies

  18. JorgeSEk说道:

    mexico pharmacies prescription drugs: mexico pharmacy – reputable mexican pharmacies online

  19. BrandonGak说道:

    medication from mexico pharmacy: mexico pharmacy – mexican mail order pharmacies

  20. DevonStolf说道:

    https://mexicanpharm24.cheap/# mexican border pharmacies shipping to usa
    canadian drugs

  21. Williambiz说道:

    erectile dysfunction natural remedies http://pharm24.pro/# cheapest ed pills online

  22. Leroytrupt说道:

    indian pharmacy paypal Order medicine from India to USA Online medicine order

  23. JorgeSEk说道:

    indian pharmacy online: indian pharm 24 – reputable indian pharmacies

  24. Leroytrupt说道:

    prices of viagra at walmart cheap medication ed treatments that really work

  25. profi-teh-remont说道:

    Сервисный центр предлагает ремонт lenovo thinkpad edge e145 цены ремонт lenovo thinkpad edge e145 в петербурге

  26. BrandonGak说道:

    cheap pills online: buy drugs – real cialis without a doctor’s prescription

  27. Williambiz说道:

    comfortis without vet prescription https://pharm24.pro/# best ed solution

  28. profi-teh-remont说道:

    Сервисный центр предлагает замена жесткого диска samsung rv509 замена дсплея samsung rv509

  29. JorgeSEk说道:

    buying prescription drugs in mexico: mexican pharmacy – medication from mexico pharmacy

  30. DevonStolf说道:

    https://pharm24.pro/# best ed pill
    natural ed medications

  31. Williambiz说道:

    how to overcome ed naturally http://mexicanpharm24.cheap/# п»їbest mexican online pharmacies

  32. profi-teh-remont说道:

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

  33. Leroytrupt说道:

    mexico drug stores pharmacies mexico pharmacy mexican pharmaceuticals online

  34. BrandonGak说道:

    erectyle dysfunction: cheap drugs online – vitamins for ed

  35. DevonStolf说道:

    http://pharm24.pro/# buy prescription drugs from canada cheap
    sexual dysfunction in men

  36. Williambiz说道:

    erectile dysfunction pills http://mexicanpharm24.cheap/# buying prescription drugs in mexico

  37. Leroytrupt说道:

    india pharmacy mail order Indian pharmacy international shipping buy medicines online in india

  38. DevonStolf说道:

    https://mexicanpharm24.cheap/# mexico drug stores pharmacies
    cheap erectile dysfunction pill

  39. JorgeSEk说道:

    buying from online mexican pharmacy: mexico pharmacy – medication from mexico pharmacy

  40. Williambiz说道:

    online medication https://mexicanpharm24.cheap/# mexican pharmaceuticals online

  41. BrandonGak说道:

    buying from online mexican pharmacy: mexican drugs – medicine in mexico pharmacies

  42. Leroytrupt说道:

    mexico pharmacies prescription drugs mexico pharmacy п»їbest mexican online pharmacies

  43. JorgeSEk说道:

    india pharmacy mail order: India pharmacy international – indianpharmacy com

  44. Leroytrupt说道:

    medicine in mexico pharmacies Legit online Mexican pharmacy buying prescription drugs in mexico

  45. Istanbul_tmea说道:

    История и развитие Istanbul International Airport, развитие аэропорта на протяжении лет.
    Интересные факты о Istanbul International Airport, о которых вы не знали.
    Строительство Istanbul International Airport, которые поражают воображение.
    Что ждет аэропорт в ближайшие годы, направления роста и совершенствования.
    Что делает аэропорт уникальным, что сделано для комфорта путешественников.
    istanbul grand airport istanbul grand airport .

  46. WilliamTub说道:

    stromectol store: stromectol best price – good price

  47. Russellwar说道:

    http://semaglutide.ink/# semaglutide online

  48. TommyJew说道:

    Visit store: paxlovid1st – paxlovid store

发表回复

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