有没有使用 WinInet c++ 进行 http 上传的好例子 图书馆

发布于 2024-07-11 16:12:19 字数 19 浏览 8 评论 0原文

我无法让我的代码工作:/

I cannot get my code to work :/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

奈何桥上唱咆哮 2024-07-18 16:12:19

最终我在 web 上找到了一些工作示例

static char szRawData[5000];
  memset(szRawData, 0x11, sizeof(szRawData));

  //
  // CIHandle is just a wrapper class for HINTERNET, that closes handle in destructor
  //
  CIHandle hIntrn = InternetOpen( "LiveUpdate"), 
                                  INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY,
                                  NULL,
                                  NULL,
                                  0);
  if (!hIntrn)
    return printf("No Internet connection: %li.\n", GetLastError());

  CIHandle hConn = InternetConnect( hIntrn, 
                                    "65.254.250.104",
                                    INTERNET_DEFAULT_HTTP_PORT,
                                    NULL,
                                    NULL,
                                    INTERNET_SERVICE_HTTP,
                                    0,
                                    NULL);
  if (!hConn)
    return printf("Connection to update server failed: %li.\n", GetLastError());

  DWORD dwOpenRequestFlags = INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP |
                             INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS |
                             INTERNET_FLAG_KEEP_CONNECTION |
                             INTERNET_FLAG_NO_AUTO_REDIRECT |
                             INTERNET_FLAG_NO_COOKIES |
                             INTERNET_FLAG_NO_CACHE_WRITE |
                             INTERNET_FLAG_NO_UI |
                             INTERNET_FLAG_RELOAD;

  CIHandle hReq = HttpOpenRequest(hConn,
                                  "POST",
                                  "upload.php",
                                  "HTTP/1.0",
                                  NULL,
                                  NULL,
                                  dwOpenRequestFlags,
                                  NULL);

  ZString strBoundary = "---------------------------autoupdater";
  ZString strContentHeader =  "Host: www.mydomain_at_powweb.com\r\n"
                              "Content-Type: multipart/form-data; boundary=";
  strContentHeader+=strBoundary;

  HttpAddRequestHeaders(hReq, strContentHeader, strContentHeader.length(), HTTP_ADDREQ_FLAG_ADD);


  ZString strHeaders;
  strHeaders.precache(16384);
  sprintf(strHeaders,
          "--%s\r\n"
          "Content-Disposition: form-data; name=\"userfile\"; "
          "filename=\"test.raw\"\r\n"
          "Content-Type: application/octet-stream\r\n\r\n",
          (LPCTSTR)strBoundary);

  tCharSeq s;//this is a just a dynamic array of bytes;
  //
  // append headers and file to request:
  //
  s.precache(16384);
  s.append(strHeaders.length(), strHeaders);
  //append with file data:
  s.append(2000, szRawData); //<------------------- depending on this size, SendRequest fails.
  //trailing end of data:
  s.append(4,"\r\n--");
  s.append(strBoundary.length(), (LPTSTR)strBoundary);
  s.append(4,"--\r\n");

  InternetSetOption(hReq, INTERNET_OPTION_USERNAME, "username\0", 9);
  InternetSetOption(hReq, INTERNET_OPTION_PASSWORD, "password\0", 9);

  if (!HttpSendRequest(hReq, NULL, 0, (void*)s.getBuffer(), s.length()))
    return printf("HttpSendRequest failed: %li.\n", GetLastError());

Eventually I found some working example on the web

static char szRawData[5000];
  memset(szRawData, 0x11, sizeof(szRawData));

  //
  // CIHandle is just a wrapper class for HINTERNET, that closes handle in destructor
  //
  CIHandle hIntrn = InternetOpen( "LiveUpdate"), 
                                  INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY,
                                  NULL,
                                  NULL,
                                  0);
  if (!hIntrn)
    return printf("No Internet connection: %li.\n", GetLastError());

  CIHandle hConn = InternetConnect( hIntrn, 
                                    "65.254.250.104",
                                    INTERNET_DEFAULT_HTTP_PORT,
                                    NULL,
                                    NULL,
                                    INTERNET_SERVICE_HTTP,
                                    0,
                                    NULL);
  if (!hConn)
    return printf("Connection to update server failed: %li.\n", GetLastError());

  DWORD dwOpenRequestFlags = INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP |
                             INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS |
                             INTERNET_FLAG_KEEP_CONNECTION |
                             INTERNET_FLAG_NO_AUTO_REDIRECT |
                             INTERNET_FLAG_NO_COOKIES |
                             INTERNET_FLAG_NO_CACHE_WRITE |
                             INTERNET_FLAG_NO_UI |
                             INTERNET_FLAG_RELOAD;

  CIHandle hReq = HttpOpenRequest(hConn,
                                  "POST",
                                  "upload.php",
                                  "HTTP/1.0",
                                  NULL,
                                  NULL,
                                  dwOpenRequestFlags,
                                  NULL);

  ZString strBoundary = "---------------------------autoupdater";
  ZString strContentHeader =  "Host: www.mydomain_at_powweb.com\r\n"
                              "Content-Type: multipart/form-data; boundary=";
  strContentHeader+=strBoundary;

  HttpAddRequestHeaders(hReq, strContentHeader, strContentHeader.length(), HTTP_ADDREQ_FLAG_ADD);


  ZString strHeaders;
  strHeaders.precache(16384);
  sprintf(strHeaders,
          "--%s\r\n"
          "Content-Disposition: form-data; name=\"userfile\"; "
          "filename=\"test.raw\"\r\n"
          "Content-Type: application/octet-stream\r\n\r\n",
          (LPCTSTR)strBoundary);

  tCharSeq s;//this is a just a dynamic array of bytes;
  //
  // append headers and file to request:
  //
  s.precache(16384);
  s.append(strHeaders.length(), strHeaders);
  //append with file data:
  s.append(2000, szRawData); //<------------------- depending on this size, SendRequest fails.
  //trailing end of data:
  s.append(4,"\r\n--");
  s.append(strBoundary.length(), (LPTSTR)strBoundary);
  s.append(4,"--\r\n");

  InternetSetOption(hReq, INTERNET_OPTION_USERNAME, "username\0", 9);
  InternetSetOption(hReq, INTERNET_OPTION_PASSWORD, "password\0", 9);

  if (!HttpSendRequest(hReq, NULL, 0, (void*)s.getBuffer(), s.length()))
    return printf("HttpSendRequest failed: %li.\n", GetLastError());
恋你朝朝暮暮 2024-07-18 16:12:19

这是 Microsoft 的一个简单示例。

   static TCHAR hdrs[] =
      _T("Content-Type: application/x-www-form-urlencoded");
   static TCHAR frmdata[] =
      _T("name=John+Doe&userid=hithere&other=P%26Q");
  static LPSTR accept[2]={"*/*", NULL};

   // for clarity, error-checking has been removed
   HINTERNET hSession = InternetOpen("MyAgent",
      INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
   HINTERNET hConnect = InternetConnect(hSession, _T("ServerNameHere"),
      INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
   HINTERNET hRequest = HttpOpenRequest(hConnect, "POST",
      _T("FormActionHere"), NULL, NULL, accept, 0, 1);
   HttpSendRequest(hRequest, hdrs, strlen(hdrs), frmdata, strlen(frmdata));
   // close any valid internet-handles

该示例来自此处

Here's a quick example from Microsoft.

   static TCHAR hdrs[] =
      _T("Content-Type: application/x-www-form-urlencoded");
   static TCHAR frmdata[] =
      _T("name=John+Doe&userid=hithere&other=P%26Q");
  static LPSTR accept[2]={"*/*", NULL};

   // for clarity, error-checking has been removed
   HINTERNET hSession = InternetOpen("MyAgent",
      INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
   HINTERNET hConnect = InternetConnect(hSession, _T("ServerNameHere"),
      INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
   HINTERNET hRequest = HttpOpenRequest(hConnect, "POST",
      _T("FormActionHere"), NULL, NULL, accept, 0, 1);
   HttpSendRequest(hRequest, hdrs, strlen(hdrs), frmdata, strlen(frmdata));
   // close any valid internet-handles

The example comes from here.

聚集的泪 2024-07-18 16:12:19

MSDN 有一个很好的示例 SAMPLE:Using HttpSendRequestEx对于大型 POST 请求
它还包含一个供HTTP服务器接收数据的ASP文件,请在msdn页面下载自解压文件“Hsrex.exe”。

MSDN has a good example SAMPLE: Using HttpSendRequestEx for Large POST Requests
it also contain a ASP file for HTTP server to receive data, please download the self-extract file 'Hsrex.exe' in msdn page.

黑寡妇 2024-07-18 16:12:19

我找不到如何使用 wininet 和 c/c++ 的简单而完整的代码,因此我从一点点开始为将来访问但无法弄清楚的人编写了一个简单而简单的 c 代码。该代码可以上传任何文件(二进制,文本,mp3 ....)到您指定的主机名,对于后端我使用php(下面的代码)。

#include<windows.h>
#include<stdio.h>
#include<wininet.h>

int main(int argc,char *argv[])
{
    if(argc!=4)
    {
        printf("USAGE:fileuploader.exe hostname scriptname filename");
        exit(1);
    }
    HANDLE hfile=CreateFile(argv[3],GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL);
    if(hfile==INVALID_HANDLE_VALUE)
    {
        printf("creatfile error %lu",GetLastError());
        exit(1);
    }
    DWORD filesize=GetFileSize(hfile,NULL);
    //STARTING PREPARING THE WININET CODE.
    PCHAR szstart = "Content-Type: multipart/form-data; boundary=----qwerty";
    PCHAR szData    = "------qwerty\r\n"
                      "Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\n"
                      "Content-Type: application/octet-stream\r\n"
                      "Content-Transfer-Encoding: binary\r\n\r\n";
    PCHAR szDataEnd = "\r\n------qwerty--\r\n";
    char szheaders[1024];
    wsprintf(szheaders,szData,"filetoupload",argv[3]);
    HINTERNET hsession,hconnect,hrequest;
    DWORD bytesread,byteswritten,contentlen;
    hsession=InternetOpen("fileuploader",INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0);
    if(!hsession)
    {
        printf("internet open error %lu",GetLastError());
        exit(1);
    }
    hconnect=InternetConnect(hsession,argv[1],INTERNET_DEFAULT_HTTP_PORT,NULL,NULL,INTERNET_SERVICE_HTTP,0,0);
    hrequest=HttpOpenRequest(hconnect,"POST",argv[2],NULL,NULL,0,0,0);
    contentlen=lstrlen(szheaders)+filesize+lstrlen(szDataEnd);
    LPBYTE pbuf=(LPBYTE)malloc(contentlen);
    CopyMemory(&pbuf[0],szheaders,lstrlen(szheaders));
    ReadFile(hfile,&pbuf[lstrlen(szheaders)],filesize,&bytesread,NULL);
    CopyMemory(&pbuf[lstrlen(szheaders)+filesize],szDataEnd,lstrlen(szDataEnd));
    HttpSendRequest(hrequest,szstart,lstrlen(szstart),pbuf,contentlen);
    char testbuf[1024];
    InternetReadFile(hrequest,testbuf,(DWORD)sizeof(testbuf),&byteswritten);
    printf("%s",testbuf);


}

这是我使用的 php 代码

<?php
if(isset($_FILES["filetoupload"]))
{
    $path="C:/xampp/htdocs/";
    $path=$path.basename($_FILES['filetoupload']['name']);
    print($path);
    if(move_uploaded_file($_FILES['filetoupload']['tmp_name'],$path))
    {
        print("upload success");
    }
    else
    {
        print("no success");

    }

}


?>

<html>
<body>
<form action="fileupload.php" method="post" enctype="multipart/form-data">  
    Select File:  
    <input type="file" name="filetoupload"/>  
    <input type="submit" value="Upload Image" name="submit"/>  
</form>  
</body>
</html>

I couldn't find an easy and complete code of how to use wininet with c/c++ so from bits and pieces i wrote an easy and simple c code for someone that visits in future and cant figure out.The code can upload any file(binary,text,mp3....) to hostname you specify,for backend i use php(below code).

#include<windows.h>
#include<stdio.h>
#include<wininet.h>

int main(int argc,char *argv[])
{
    if(argc!=4)
    {
        printf("USAGE:fileuploader.exe hostname scriptname filename");
        exit(1);
    }
    HANDLE hfile=CreateFile(argv[3],GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL);
    if(hfile==INVALID_HANDLE_VALUE)
    {
        printf("creatfile error %lu",GetLastError());
        exit(1);
    }
    DWORD filesize=GetFileSize(hfile,NULL);
    //STARTING PREPARING THE WININET CODE.
    PCHAR szstart = "Content-Type: multipart/form-data; boundary=----qwerty";
    PCHAR szData    = "------qwerty\r\n"
                      "Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\n"
                      "Content-Type: application/octet-stream\r\n"
                      "Content-Transfer-Encoding: binary\r\n\r\n";
    PCHAR szDataEnd = "\r\n------qwerty--\r\n";
    char szheaders[1024];
    wsprintf(szheaders,szData,"filetoupload",argv[3]);
    HINTERNET hsession,hconnect,hrequest;
    DWORD bytesread,byteswritten,contentlen;
    hsession=InternetOpen("fileuploader",INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0);
    if(!hsession)
    {
        printf("internet open error %lu",GetLastError());
        exit(1);
    }
    hconnect=InternetConnect(hsession,argv[1],INTERNET_DEFAULT_HTTP_PORT,NULL,NULL,INTERNET_SERVICE_HTTP,0,0);
    hrequest=HttpOpenRequest(hconnect,"POST",argv[2],NULL,NULL,0,0,0);
    contentlen=lstrlen(szheaders)+filesize+lstrlen(szDataEnd);
    LPBYTE pbuf=(LPBYTE)malloc(contentlen);
    CopyMemory(&pbuf[0],szheaders,lstrlen(szheaders));
    ReadFile(hfile,&pbuf[lstrlen(szheaders)],filesize,&bytesread,NULL);
    CopyMemory(&pbuf[lstrlen(szheaders)+filesize],szDataEnd,lstrlen(szDataEnd));
    HttpSendRequest(hrequest,szstart,lstrlen(szstart),pbuf,contentlen);
    char testbuf[1024];
    InternetReadFile(hrequest,testbuf,(DWORD)sizeof(testbuf),&byteswritten);
    printf("%s",testbuf);


}

and here is the php code i use along with it

<?php
if(isset($_FILES["filetoupload"]))
{
    $path="C:/xampp/htdocs/";
    $path=$path.basename($_FILES['filetoupload']['name']);
    print($path);
    if(move_uploaded_file($_FILES['filetoupload']['tmp_name'],$path))
    {
        print("upload success");
    }
    else
    {
        print("no success");

    }

}


?>

<html>
<body>
<form action="fileupload.php" method="post" enctype="multipart/form-data">  
    Select File:  
    <input type="file" name="filetoupload"/>  
    <input type="submit" value="Upload Image" name="submit"/>  
</form>  
</body>
</html>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文