我正在尝试使用C进行邮政请求,因为我需要可执行文件才能在.NET或其他库上不依赖。
执行下面的代码时,服务器都会获得两个预期JSON字符串的零值:
void MakePostReq1(
const char* verb,
const char* hostname,
int port,
const char* resource,
const char* opt_urlencoded,
string& response)
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
cout << "WSAStartup failed.n";
exit(1);
}
SOCKET Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct hostent *host;
host = gethostbyname(hostname);
SOCKADDR_IN SockAddr;
SockAddr.sin_port = htons(port);
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
cout << "Connecting...n";
if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0)
{
cout << "Could not connect";
exit(1);
}
cout << "Connected.n";
string json1 = "";
json1.append("------------------------e661208454117a87");
json1.append("rn");
json1.append("Content-Disposition: form-data; name="jsonObject"rn");
json1.append("Content-Type: application/jsonrn");
json1.append("rn");
json1.append("{ jsonObject: "This is a jsonObject" }");
json1.append("rn");
json1.append("rn");
string json2 = "";
json2.append("------------------------e661208454117a87");
json2.append("rn");
json2.append("Content-Disposition: form-data; name="jsonEventObject"rn");
json2.append("Content-Type: application/jsonrn");
json2.append("rn");
json2.append("{ jsonEventObject: "This is a jsonEventObject" }");
json2.append("rn");
json2.append("rn");
string trailer = "";
trailer.append("------------------------e661208454117a87");
trailer.append("rn");
// Build request
string req = "POST"; // GET | POST
req.append(" ");
req.append(resource);
req.append(" HTTP/1.1rn");
req.append("Host: ");
req.append(hostname);
req.append(":");
req.append(to_string(port));
req.append("rn");
req.append("Cache-Control: no-cachern");
req.append("Content-length: ");
char size[5];
sprintf(size, "%d", json1.size() + json2.size() + trailer.size());
//sprintf(size, "%d", 319);
req.append( size );
req.append("rn");
req.append("Content-Type: multipart/form-data; boundary="------------------------e661208454117a87"rnrn");
// add json strings
req.append(json1);
req.append(json2);
req.append(trailer);
cout << endl;
cout << "Request size: " << req.size() << endl;
cout << "Request " << endl << req << endl;
send(Socket, req.c_str(), req.size(), 0);
closesocket(Socket);
WSACleanup();
}
在这一行:
req.append("Content-Type: multipart/form-data; boundary="------------------------e661208454117a87"rnrn");
从边界上删除引号:
req.append("Content-Type: multipart/form-data; boundary=------------------------e661208454117a87rnrn");
引号被解释为边界的一部分,因此您以下数据边界未识别。