過去幾天我一直在嘗試POST使用 Win32 API 向我的 SpringBoot 應用程式發送 HTTP 請求,但我總是收到相同的錯誤。該請求multipart由一個二進制檔案和一個 JSON 組成。通過 Postman 發送請求沒有問題,我能夠正確接收檔案和 JSON。
我查看了幾乎所有關于如何使用 WinHTTP 構建 HTTP 請求的帖子和問題,似乎他們都在做我所做的事情,但由于某種原因,我收到了一個奇怪的構造請求,如下面的 WireShark 影像所示.
似乎請求沒有被識別為幾個部分,而是被識別為一大塊資料。
在 WireShark 中查看使用郵遞員發送的正確請求,表明該請求由所有部分組成,就像它應該的那樣。
這是我的代碼:
LPCWSTR additionalHeaders = L"Accept: application/json\r\nContent-Type: multipart/form-data; boundary=----------------------------346435246262465368257857\r\n";
if (data->type == RequestType::MULTIPART) {
size_t filesize = 0;
char* fileData = fileToString("img.png", "rb", &filesize);
WinHttpAddRequestHeaders(hRequest, additionalHeaders, -1L, WINHTTP_ADDREQ_FLAG_ADD);
char postData1[] =
"----------------------------346435246262465368257857\r\n"
"Content-Disposition: form-data; name=\"file\"; filename=\"img.png\"\r\n"
"Content-Type: image/png\r\n\r\n";
char postData2[] =
"\r\n----------------------------346435246262465368257857\r\n"
"Content-Disposition: form-data; name=\"newData\"\r\n"
"Content-Type: application/json\r\n\r\n"
"{\"dataType\":\"DEVICE_SETTINGS\"}"
"\r\n----------------------------346435246262465368257857--\r\n";
if (hRequest)
bResults = WinHttpSendRequest(hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS,
0, WINHTTP_NO_REQUEST_DATA, 0,
lstrlenA(postData1) lstrlenA(postData2) filesize, NULL);
DWORD dwBytesWritten = 0;
if (bResults)
bResults = WinHttpWriteData(hRequest, postData1, lstrlenA(postData1), &dwBytesWritten);
if (bResults)
bResults = WinHttpWriteData(hRequest,(LPCVOID) fileData, filesize, &dwBytesWritten);
if (bResults)
bResults = WinHttpWriteData(hRequest, postData2, lstrlenA(postData2), &dwBytesWritten);
}
errorMessageID = ::GetLastError();
// End the request.
if (bResults)
bResults = WinHttpReceiveResponse(hRequest, NULL);
使用 Postman 發送的有效請求
使用 WinHTTP 發送的請求無效
郵遞員配置1
郵遞員配置2
SpringBoot 控制器
這是我在 SpringBoot 應用程式日志中收到的錯誤:
2022-03-04 14:48:34.520 WARN 25412 --- [nio-8010-exec-6] .wsmsDefaultHandlerExceptionResolver:已解決 [org.springframework.web.multipart.support.MissingServletRequestPartException:所需的請求部分“檔案”不存在]
我非常感謝您在這里解決這個謎團的任何幫助!
uj5u.com熱心網友回復:
postdata1您和字串中的 MIME 邊界postdata2不完整,這就是 WireShark 和 SpringBoot 應用程式無法正確決議您的資料的原因。
正文資料中的每個 MIME 邊界都必須以前導開頭--,后跟Content-Type您在'sboundary屬性中指定的值,然后是最終終止邊界中的尾隨--。
讓我們看一個根本不使用任何值的更簡單的示例-,boundary這應該會讓您更清楚:
POST /resource HTTP/1.1
Host: ...
Content-Type: multipart/form-data; boundary=myboundary\r\n";
--myboundary
Content-Disposition: form-data; name="file"; filename="img.png"
Content-Type: image/png
<file data>
--myboundary
Content-Disposition: form-data; name="newData"
Content-Type: application/json
<json data>
--myboundary--
正如您在上面看到的,在 Postman 的資料中,前導--出現在每個邊界上,但在您的資料中缺失:
Postman 的
boundary屬性宣告了一個有26 個前導-的值,并且正文資料中的每個邊界都以28個前導開始-。您的
boundary屬性宣告了一個具有28個前導-的值,并且正文資料中的每個邊界也以28個前導開始-。
--因此,資料中的每個邊界都缺少前導。
只需從您的屬性-中的值中洗掉 2 s,就可以了。Content-Typeboundary
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/440061.html
上一篇:SetWindowsHookEx(WH_SHELL,...):事件HSHELL_WINDOWREPLACED是什么意思?
