[英]Sending a POST request locally in C++ on Windows
我在同一台PC上(在Windows 10上)有一個c ++客戶端和golang服務器,我希望客戶端將POST請求發送到服務器。 我要發送的請求是/ test一個。 兩個項目都可以編譯並運行良好,但是即使服務器正在顯示請求,客戶端也無法處理請求
"HTTP-GA-SERVER: POST Successfully sent"
這是C ++代碼:
#include <winsock2.h>
#include "ga-http-post.h"
int sendPostToMushroom(HttpRequestType req, void* metrics)
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
std::cout << "WSAStartup failed." << std::endl;
return 1;
}
SOCKET Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
SOCKADDR_IN SockAddr;
SockAddr.sin_port=htons(8080);
SockAddr.sin_family=AF_INET;
SockAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
std::cout << "HTTP-GA: Connecting..." << std::endl;
if (Socket < 0) {
std::cout << "HTTP-GA: Error creating socket: " << WSAGetLastError() << std::endl;
return 1;
}
if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0){
std::cout << "HTTP-GA: Error connecting: " << WSAGetLastError() << std::endl;
return 1;
}
std::cout << "HTTP-GA: Connected to " << inet_ntoa(SockAddr.sin_addr) << std::endl;
char buffer[2048];
strcpy(buffer,"POST /test HTTP/1.1\n");
if (send(Socket,buffer, strlen(buffer),0) != strlen(buffer))
{
std::cout << "HTTP-GA: Error sending:" << WSAGetLastError() << std::endl;
return 1;
}
closesocket(Socket);
WSACleanup();
std::cout << "HTTP-GA: POST Successfully sent" << std::endl;
return 0;
}
和golang代碼:
func (a *Agent) runGaHTTPHandler() {
fmt.Println("HTTP : Init HTTP Server")
http.HandleFunc("/ready", a.handleServerReady)
http.HandleFunc("/unavailable", a.handleServerUnavailable)
http.HandleFunc("/connected", a.handleClientConnected)
http.HandleFunc("/disconnected", a.handleServerUnavailable)
http.HandleFunc("/MetricsCollected", a.handleMetrics)
http.HandleFunc("/test", a.handleTest)
fmt.Println("HTTP : Listen and serve")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func (a *Agent) handleTest(w http.ResponseWriter, r *http.Request) {
fmt.Print("HTTP : Test successful\n")
}
編輯:C ++代碼已更改,仍然無法正常工作
編輯
在客戶端代碼中,嘗試更改: strcpy(buffer,"POST /test HTTP/1.1\\n");
到strcpy(buffer,"POST /test HTTP/1.1\\r\\nHost: localhost\\r\\n\\r\\n");
HTTP / 1.1要求存在Host
HTTP標頭; 在標題之后,應該有一個額外的換行符( \\r\\n
)。 當然,如果需要,可以將localhost
更改為實際的主機名。
[關於Go http服務器代碼的先前答案]
在handleTest
函數中,您需要寫入http.ResponseWriter w
或使用其WriteHeader
和Write
函數。 當前,代碼中的fmt.Print
很可能會在啟動Go服務器的終端中打印字符串,但不會將其發送給客戶端。 嘗試使用以下(簡化)版本的Go程序:
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/test", handleTest)
fmt.Println("HTTP : Listen and serve")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handleTest(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("HTTP : Test successful\n"))
}
當啟動Go服務器時,客戶端應該收到一個類似curl的響應(您也可以通過瀏覽器訪問它進行測試):
$ curl http://localhost:8080/test HTTP : Test successful
您可以在net / http包的文檔中看到ResponseHeader
的Write
和WriteHeader
函數的描述: https ://golang.org/pkg/net/http/#ResponseWriter
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.