前段时间,我做了一个非常简单的方法,可以发出http请求并返回响应。这就像我想要的那样工作,但现在我想再次使用它,但我突然遇到了一个我似乎无法弄清楚的问题。每次我发出请求时,它都会返回 错误 503:服务不可用。
有时有效,有时无效。
我注意到如果我在关闭连接后放置一个断点并稍等片刻继续,没有问题,一切正常。所以我的猜测是这与服务器的时间/延迟有关。
这个事情谁有经验?
提前致谢!
string HttpHelper::HttpGet(string host, string path)
{
WSADATA wsaData;
int result;
// Initialize Winsock
result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0)
throw SocketError(L"WSAStartUp", result);
// Resolve the server address and port
addrinfo * pAddrInfo;
result = getaddrinfo(host.c_str(), "80", 0, &pAddrInfo);
if (result != 0)
throw SocketError(L"addrinfo", result);
//Create the socket
SOCKET sock = socket(pAddrInfo->ai_family, pAddrInfo->ai_socktype, pAddrInfo->ai_protocol);
if (sock == INVALID_SOCKET)
throw SocketError(L"Socket", WSAGetLastError());
// Connect to server.
result = connect(sock, pAddrInfo->ai_addr, pAddrInfo->ai_addrlen);
if (result != 0)
throw SocketError(L"Connect", WSAGetLastError());
const string request = "GET " + path + " HTTP/1.1\nHost: " + host + "\n\n";
// Send an initial buffer
result = send(sock, request.c_str(), request.size(), 0);
if (result == SOCKET_ERROR)
throw SocketError(L"Send", WSAGetLastError());
// shutdown the connection since no more data will be sent
result = shutdown(sock, SD_SEND);
if (result == SOCKET_ERROR)
throw SocketError(L"Close send connection", WSAGetLastError());
// Receive until the peer closes the connection
string response;
char buffer[50];
int bytesRecv = 0;
for (;;)
{
result = recv(sock, buffer, sizeof(buffer), 0);
if (result == SOCKET_ERROR)
throw SocketError(L"Recv", WSAGetLastError());
if (result == 0)
break;
response += string(buffer, result);
wstringstream stream;
stream << L"HttpGet() > Bytes received: " << bytesRecv;
DebugLog::Log(stream.str(), LogType::INFO);
bytesRecv += result;
}
wstringstream stream;
stream << L"HttpGet() > Bytes received: " << bytesRecv;
DebugLog::Log(stream.str(), LogType::INFO);
// cleanup
result = closesocket(sock);
if (result == SOCKET_ERROR)
throw SocketError(L"Closesocket", WSAGetLastError());
result = WSACleanup();
if (result == SOCKET_ERROR)
throw SocketError(L"WSACleanup", WSAGetLastError());
freeaddrinfo(pAddrInfo);
DebugLog::Log(L"HttpGet() > Cleanup Successful ", LogType::INFO);
return response;
}
wstring SocketError::ErrorMessage(const wstring & context, const int errorCode) const
{
wchar_t buf[1024];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, errorCode, 0, buf, sizeof(buf), 0);
wchar_t * newLine = wcsrchr(buf, '\r');
if (newLine) *newLine = '\0';
wstringstream stream;
stream << L"Socket error in " << context << L" (" << errorCode << L"): " << buf;
return stream.str();
}
原文由 Simon Coenen 发布,翻译遵循 CC BY-SA 4.0 许可协议
很难说…
下面是一段简单通用的winsock代码,大家可以试试,只是看看使用这段代码时是否也存在问题。