首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Http请求: Winsock

Http请求: Winsock
EN

Stack Overflow用户
提问于 2014-04-22 19:17:27
回答 1查看 1K关注 0票数 0

在编写http请求时,我使用Visual作为c++,现在我的代码是这样的,

代码语言:javascript
复制
#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是这样的

代码语言:javascript
复制
<?php
session_start();
$username = urldecode($_POST['username']);
$password = urldecode($_POST['password']);

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

现在我有一个关于php区域的问题,它没有接收信息并再次打印出来,让我们看看,可能会有什么问题呢?

EN

回答 1

Stack Overflow用户

发布于 2014-04-22 23:23:38

HTTP请求中有几个错误。

  1. 您需要使用\r\n而不是\n
  2. Content - Type需要成为Content-Type
  3. localost需要成为localhost
  4. content-Length:32需要是Content-Length: 34

试试这个:

代码语言:javascript
复制
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;
}

如果有更好的替代方案,比如微软的WinInet/WinHTTP、curl库等,您真的不应该像这样从头开始编写自己的HTTP代码,让他们为您做艰苦的工作。

代码语言:javascript
复制
#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;
}

代码语言:javascript
复制
#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(); 
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23228315

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档