Http请求:Winsock

时间:2014-04-22 19:17:28

标签: http

编码http请求时,我使用Visual Studio for c ++,现在我的代码就是这样,

#define WIN32_LEAN_AND_MEAN

#include "stdafx.h"
#include <cstdio>
#include <cstdlib>
#include <Winsock2.h>
#include <WS2tcpip.h>
#include <windows.h>

#pragma comment (lib,"ws2_32")

int _tmain(int argc, _TCHAR* argv[])
    {
      WSADATA wsaData;
      int iResult = WSAStartup(MAKEWORD(2,2),&wsaData);
      SOCKET m_socket;
      m_socket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
      if(m_socket==INVALID_SOCKET)
        {
        printf("Invalid Socket :WSAGetLastError()");
            }
    sockaddr_in clientService;
    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr("127.0.0.1");
    clientService.sin_port = htons(5357);
    LPHOSTENT host = gethostbyname("72.144.89.32");

    if(connect(m_socket,(SOCKADDR*)&clientService,sizeof(clientService))==SOCKET_ERROR)
    {
      printf("Connection Failure");
      WSACleanup();
      return 1;
    }

    char buffer[2048];

    strcpy(buffer,"POST /dbarea.php HTTP/1.1\n");
    strcat(buffer,"Content - Type:application/x-www-form-urlencoded\n");
    strcat(buffer,"Host: localost\n");
    strcat(buffer,"content-Length:32\n");
    strcat(buffer,"\n");
    strcat(buffer,"username=emeka1&password=laikan112");
    //int n = write(SOCKADDR*,buffer,strlen(buffer));

    printf("Data Sent Successfully..");

    return 0;

        }

现在我的php就像这样

<?php
session_start();
$username = urldecode($_POST['username']);
$password = urldecode($_POST['password']);

echo "Username: $username\nPassword:$password";
?>

现在我在php区域有一个问题,它没有收到信息并再次打印给我们看,可能是什么问题?

1 个答案:

答案 0 :(得分:0)

您的HTTP请求中存在多个错误。

  1. 您需要使用\r\n代替\n

  2. Content - Type需要Content-Type

  3. localost需要localhost

  4. content-Length:32需要Content-Length: 34

  5. 试试这个:

    int _tmain(int argc, _TCHAR* argv[])
    {
        WSADATA wsaData;
        int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
        if (iResult != 0)
        {
            printf("WinSock startup error: %d\n", iResult);
            return 1;
        }
    
        SOCKET m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (m_socket == INVALID_SOCKET)
        {
            printf("Socket creation error: %d\n", WSAGetLastError());
            WSACleanup();
            return 1;
        }
    
        sockaddr_in clientService = {0};
        clientService.sin_family = AF_INET;
        clientService.sin_addr.s_addr = inet_addr("127.0.0.1");
        clientService.sin_port = htons(5357);
    
        if (connect(m_socket, (SOCKADDR*)&clientService, sizeof(clientService)) == SOCKET_ERROR)
        {
            printf("Connection error: %d\n", WSAGetLastError());
            closesocket(m_socket);
            WSACleanup();
            return 1;
        }
    
        char buffer[2048];
    
        strcpy(buffer, "POST /dbarea.php HTTP/1.1\r\n");
        strcat(buffer, "Content-Type: application/x-www-form-urlencoded\r\n");
        strcat(buffer, "Host: localhost:5357\r\n");
        strcat(buffer, "Content-Length: 34\r\n");
        strcat(buffer, "\r\n");
        strcat(buffer, "username=emeka1&password=laikan112");
    
        char ptr = buffer;
        int len = strlen(buffer);
    
        do
        {
            int n = send(m_socket, ptr, len, 0);
            if (n < 1)
            {
                if (n == SOCKET_ERROR)
                    printf("Send error: %d\n", WSAGetLastError());
                else
                    printf("disconnected by server\n");
    
                closesocket(m_socket);
                WSACleanup();
                return 1;
            }
    
            ptr += n;
            len -= n;
        }
        while (len > 0);
    
        printf("Data Sent Successfully..\n");
    
        closesocket(m_socket);
        WSACleanup();
    
        return 0;
    }
    

    当有更好的替代方案时,你真的不应该从头开始编写自己的HTTP代码,例如微软的WinInet / WinHTTP API,curl库等。让他们为你努力工作。

    #include <WinInet.h>
    #include <tchar.h>
    
    void ReportWinInetError(const char *operation)
    {
        DWORD dwErr = GetLastError();
        if (dwErr == ERROR_INTERNET_EXTENDED_ERROR)
        {
            LPTSTR szBuffer = NULL;
            DWORD dwLength = 0;
    
            BOOL bRet = InternetGetLastResponseInfo(&dwErr, NULL, &dwLength);
            if ((bRet == FALSE) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER))
            {
                szBuffer = new TCHAR[dwLength+1];
                bRet = InternetGetLastResponseInfo(&dwErr, szBuffer, &dwLength);
            }
    
            if (bRet)
                _tprintf(_T("WinInet error while %hs: %u %*s"), operation, dwErr, dwLength, szBuffer);
            else
                printf("Unknown WinInet error while %s", operation);
    
            delete[] szBuffer;
        }
        else
            printf("WinInet error while %s: %u", operation, dwErr);
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        HINTERNET hInternet = InternetOpen(TEXT("MyApp"), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
        if (!hInternet)
        {
            ReportWinInetError("opening session");
            return 1;
        }
    
        HINTERNET hConnect = InternetConnect(hInternet, TEXT("127.0.0.1"), 5357, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
        if (!hConnect)
        {
            ReportWinInetError("connecting session");
            InternetCloseHandle(hInternet);
            return 1;
        }
    
        HINTERNET hRequest = HttpOpenRequest(hConnect, TEXT("POST"), TEXT("/dbarea.php"), TEXT("HTTP/1.1"), NULL, NULL, 0, 0);
        if (!hRequest)
        {
            ReportWinInetError("opening request");
            InternetCloseHandle(hConnect);
            InternetCloseHandle(hInternet);
            return 1;
        }
    
        if (!HttpSendRequest(hRequest, TEXT("Content-Type: application/x-www-form-urlencoded"), -1, "username=emeka1&password=laikan112", 34))
        {
            ReportWinInetError("sending request");
            InternetCloseHandle(hRequest);
            InternetCloseHandle(hConnect);
            InternetCloseHandle(hInternet);
            return 1;
        }
    
        printf("Data Sent Successfully..\n");
    
        InternetCloseHandle(hRequest);
        InternetCloseHandle(hConnect);
        InternetCloseHandle(hInternet);
    
        return 0;
    }
    

    #include <curl/curl.h> 
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        CURLCode ret = curl_global_init(CURL_GLOBAL_DEFAULT);
        if (ret != CURLE_OK)
        {
            printf("Curl init error: %d\n", ret);
            return 1;
        }
    
        CURL *curl = curl_easy_init(); 
        if (!curl)
        {
            printf("Curl request creation error\n");
            curl_global_cleanup(); 
            return 1;
        }
    
        curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1:5357/dbarea.php"); 
        curl_easy_setopt(curl, CURLOPT_POST, 1); 
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "username=emeka1&password=laikan112");
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, -1);
    
        ret = curl_easy_perform(curl); 
        if (ret != CURLE_OK)
        {
            printf("Curl send error: %d\n", ret);
            curl_easy_cleanup(curl); 
            curl_global_cleanup(); 
            return 1;
        }
    
        printf("Data Sent Successfully..\n");
    
        curl_easy_cleanup(curl); 
        curl_global_cleanup(); 
    }