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

/ 4,087评论 / 17423阅读 / 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. Derekjup说道:

    can i get clomid without prescription: buy clomid – where can i get clomid now

  2. Brandenven说道:

    cheap priligy: dapoxetine online – Priligy tablets

  3. StevenWearo说道:

    cost generic clomid pills: clomid purchase online rex pharm – where to buy generic clomid tablets

  4. StevenWearo说道:

    prednisone 20 mg prices: ray pharm – buy prednisone online usa

  5. Brandenven说道:

    cheap priligy: priligy maxpharm – buy dapoxetine online

  6. Top Apps to Make Money in Pakistan, For Extra Income, Secret Methods to Make Money in Pakistan, To Improve Your Financial Situation, That Are Suitable for Everyone, Is it possible to earn money in Pakistan through applications?, which you need to know, Modern ways to earn money in Pakistan through applications, Passive income in Pakistan through applications: myth or reality?, Interesting platforms for making money in Pakistan, Accurate methods of making money in Pakistan, to increase financial well-being, to increase income, for making money quickly, for making money without investment, with a high level of security, for making money at any time of the day, Interesting apps for earning money in Pakistan: choose the bestbest earning app in pakistan best online earning websites in pakistan .

  7. Brandenven说道:

    generic clomid tablets: clomid – generic clomid tablets

  8. Most Popular Apps to Make Money in Pakistan, Easy Money Making in Pakistan Through Apps, Unique Ways to Make Money in Pakistan, Optimal Apps to Make Money in Pakistan, The most effective applications for earning money in Pakistan, Facts about earning money in Pakistan through mobile applications, Safe ways to earn money in Pakistan through applications, Innovative platforms for earning money in Pakistan, which change the idea of ????earning money, to increase financial flow, which will help you achieve your financial goal, Updated platforms for making money in Pakistan, How to make money in Pakistan using mobile apps: simple and profitable, with great potential for earning, with guaranteed payments, The easiest apps for making money in Pakistan, which bring real money, Top ways to earn money in Pakistan through apps: tips andbest online earning websites in pakistan best earning app in pakistan .

  9. Derekjup说道:

    buy priligy: max pharm – buy dapoxetine online

  10. Derekjup说道:

    can you buy prednisone over the counter uk: prednisone – prednisone brand name in usa

  11. Most Popular Apps to Make Money in Pakistan, Worth Trying, That Will Change Your Financial Life, To Improve Your Financial Situation, The most effective applications for earning money in Pakistan, for quick earnings of additional funds, Verified applications for earning money in Pakistan, for a calm earnings, Convenient ways to make passive income in Pakistan, Simple ways to make money in Pakistan through mobile apps, Effective strategies for making money in Pakistan through apps, to increase financial well-being, How to make money in Pakistan using mobile apps: simple and profitable, for making money quickly, which will suit every user, Popular apps for making money in Pakistan: choose the best, which bring real money, to increase incomebest online earning websites in pakistan how to earn money online in pakistan for students .

  12. StevenWearo说道:

    prednisone online india: Prednisone Without Prescription – buy prednisone online from canada

  13. Georgetam说道:

    курсы по охране труда дистанционно в москве охрана труда обучение дистанционно цена

  14. Brandenven说道:

    rexall pharmacy amoxicillin 500mg: amoxil – amoxicillin 500mg no prescription

  15. StevenWearo说道:

    can you buy cheap clomid without rx: clomid – where to get generic clomid without dr prescription

  16. Узнай все о варикоцеле левого яичка степени варикоцеле

  17. Derekjup说道:

    clomid sale: generic clomid – can you buy clomid without prescription

  18. Brandenven说道:

    get generic clomid tablets: rexpharm – can i order cheap clomid prices

  19. Bradleyarrip说道:

    buy amoxicillin online mexico buy amoxil online amoxicillin cost australia

  20. StevenWearo说道:

    6 prednisone: Prednisone Without Prescription – order prednisone 10 mg tablet

  21. Тут можно преобрести сейф для ружья цена сейфы под оружие

  22. Тут можно преобрести купить сейф для карабина сейф для оружия цена

  23. Bradleyarrip说道:

    prednisone 10 mg coupon prednisoneraypharm prednisone 10 mg brand name

  24. Узнай все о варикоцеле диагностика варикоцеле 2 степени

  25. StevenWearo说道:

    Priligy tablets: buy dapoxetine online – buy dapoxetine online

  26. Brandenven说道:

    cheap clomid price: rex pharm – clomid without prescription

发表回复

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